Cod sursa(job #714511)

Utilizator mihaipopa12Popa Mihai mihaipopa12 Data 15 martie 2012 19:58:56
Problema Nums Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.81 kb
#include<stdio.h>
#include<algorithm>
#include<cstring>

#define maxdim 100005

using namespace std;

FILE*f=fopen("nums.in","r");
FILE*g=fopen("nums.out","w");

int n,nr,poz,s;
int tip[maxdim],Q[maxdim],Ind[maxdim],Poz[maxdim],L[maxdim],coresp[maxdim],fr[maxdim];
int Arb[4*maxdim];
char *A[maxdim];
char sir[maxdim];

inline int comp ( const int &a , const int &b , const int &l1 , const int &l2 ){
	char *p1 = A[a]; char *p2 = A[b];
	
	if ( l1 != l2 ){
		if ( l1 < l2 )	return -1;
		return 1;
	}
	
	for ( int i = 1 ; i <= l1 ; ++i ){
		if ( p1[i] < p2[i] ){
			return -1;
		}
		if ( p1[i] > p2[i] ){
			return 1;
		}
	}
	
	return 0;
}

struct cmp{
	inline bool operator () ( const int &a , const int &b ){
		if ( L[a] != L[b] ){
			return L[a] < L[b];
		}
		for ( int i = 1 ; i <= L[a] ; ++i ){
			if ( A[a][i] < A[b][i] ){
				return 1;
			}
			if ( A[a][i] > A[b][i] ){
				return 0;
			}
		}
		return 1;
	}
};

struct cmp2{
	inline bool operator () ( const int &a , const int &b ){
		return L[a] < L[b];
	}
};

void update ( int nod , int st , int dr ){
	
	if ( st == dr ){
		Arb[nod] = 1;
		return ;
	}
	
	int mij = (st + dr) >> 1;
	int nodst = nod << 1;
	int noddr = nodst + 1;
	
	if ( poz <= mij ){
		update(nodst,st,mij);
	}
	else{
		update(noddr,mij+1,dr);
	}
	
	Arb[nod] = Arb[nodst] + Arb[noddr];
}

void query ( int nod , int st , int dr ){
	
	if ( st == dr ){
		poz = st;
		return ;
	}
	
	int mij = (st + dr) >> 1;
	int nodst = nod << 1;
	int noddr = nodst + 1;
	
	if ( s <= Arb[nodst] ){
		query(nodst,st,mij);
	}
	else{
		s -= Arb[nodst];
		query(noddr,mij+1,dr);
	}
}

int main () {
	
	fscanf(f,"%d",&n);
	
	int max_l = 0;
	for ( int i = 1 ; i <= n ; ++i ){
		fscanf(f,"%d ",&tip[i]);
		if ( tip[i] ){
			fscanf(f,"%s",sir+1); ++nr;
			int l = strlen(sir+1);
			A[nr] = new char[l+3]; L[nr] = l; ++fr[l]; if ( l > max_l )	max_l = l;
			for ( int j = 1 ; j <= l ; ++j ){
				A[nr][j] = sir[j];
			}
			A[nr][l+1] = 0; Ind[nr] = nr; Poz[i] = nr;
		}
		else{
			fscanf(f,"%d",&Q[i]);
		}
	}
	
	sort(Ind+1,Ind+nr+1,cmp2());
	
	int back = 0;
	for ( int i = 1 ; i <= max_l ; ++i ){
		sort(Ind+back+1,Ind+back+fr[i]+1,cmp());
		back += fr[i];
	}
	
	for ( int i = 1 ; i <= nr ; ++i ){
		if ( i == 1 || comp(Ind[i],Ind[i-1],L[Ind[i]],L[Ind[i-1]]) != 0 ){
			Poz[Ind[i]] = Poz[Ind[i-1]] + 1;
			coresp[Poz[Ind[i]]] = Ind[i];
		}
		else{
			Poz[Ind[i]] = Poz[Ind[i-1]];
			coresp[Poz[Ind[i]]] = Ind[i];
		}
	}
	
	int nr_aux = 0; int nr_elem = Poz[Ind[nr]];
	for ( int i = 1 ; i <= n ; ++i ){
		if ( tip[i] ){
			++nr_aux;
			poz = Poz[nr_aux];
			update(1,1,nr_elem);
		}
		else{
			poz = 0; s = Q[i];
			query(1,1,nr_elem);
			fprintf(g,"%s\n",A[coresp[poz]]+1);
		}
	}
	
	fclose(f);
	fclose(g);
	
	return 0;
}