Cod sursa(job #781173)

Utilizator crushackPopescu Silviu crushack Data 23 august 2012 21:12:47
Problema Nums Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.47 kb
#include <stdio.h>
#include <string.h>
#define zeros(x) ( x&(x-1)^x )
#define LMax 100010

const char IN[]="nums.in",OUT[]="nums.out";

struct node{
	int count;
	node *next[10];
	node(){
		memset(next,0,sizeof(next));
		count=0;
	}
} *T[LMax];

int N,rest;
int arb[LMax];
char s[LMax];

void add(node *T,char *s){

	++T->count;
	for (;*s;++s)
	{
		if (!T->next[*s-'0'])
			T->next[*s-'0']=new node;
		++T->next[*s-'0']->count;
		T=T->next[*s-'0'];
	}

}

void get(node *T,int k){

	int i;
	while (T)
	{
		for (i=0;i<10;++i)
			if (T->next[i] && k>T->next[i]->count)
				k-=T->next[i]->count;
			else if (T->next[i])
				break;
		if (i<10)printf("%d",i);
		T=T->next[i-(i>=10)];
	}
	printf("\n");
}

void add(int x,int v=1){
	for (;x<LMax;x+=zeros(x))
		arb[x]+=v;
}

int query(int x){
	int ret=0;
	for (;x>0;x-=zeros(x))
		ret+=arb[x];
	return ret;
}

int search(int val){

	int i,step;
	for (step=1;step<LMax;step<<=1);
	for (i=0;step;step>>=1)
		if (i+step<LMax && val>=arb[i+step])
		{
			i+=step;val-=arb[i];
			if (!val) return i;
		}
	return i;
}

int main()
{
	int i,c,k,l;
	freopen(IN,"r",stdin);
	scanf("%d",&N);
	freopen(OUT,"w",stdout);

	for (i=0;i<LMax;++i) T[i]=new node;
	while (N--)
	{
		scanf("%d",&c);
		if (c==1){
			scanf("%s",s);
			l=strlen(s);
			add(l);
			add(T[l],s);
		}
		else{
			scanf("%d",&k);l=0;
			l=search(k-1)+1;
			rest=k-query(l-1);
			get(T[l],rest);
		}
	}
	return 0;
}