Cod sursa(job #522072)

Utilizator crushackPopescu Silviu crushack Data 14 ianuarie 2011 11:03:11
Problema Nums Scor 5
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.43 kb
#include <stdio.h>
#include <string.h>
#define NMax 100005

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

int N;
char s[NMax];

struct nod{
	int x;
	nod *p[10];
	nod()
	{
		x=0;
		memset(p,0,sizeof(p));
	}
};

int LMax=0;
nod *root=0;
nod *p[NMax];

void insert(char *s)
{
	int i,L=strlen(s),ct=0;
	nod *node;
	while (LMax<L)
	{
		node=root;
		root=NULL;
		root=new nod;
		root->p[0]=node;
		if (node)
			root->x=node->x;
		++LMax;
		p[LMax]=root;
	}
	node=p[L];
	for (i=0;i<L && node;++i)
	{
		if (!node->p[ s[i] - '0'])
			node->p[ s[i]- '0' ]=new nod,++ct;
		node= node->p[ s[i] - '0'];
	}
	node=p[L];
	if (ct && node)
	{
		++node->x;
		for (i=0;i<L && node;++i)
		{
			node= node->p[ s[i] - '0'];
			++node->x;
		}
	}
}

void Query(int k)
{
	int i,j,lj=0,L,kp=k;
	for (i=1;i<=LMax && kp-p[i]->x>0;++i)
		kp-= p[i]->x;
	nod *node= p[i];
	L=i;
	
	for (i=0;i<L && node;++i)
	{
		for (j=0;j<10;++j)
			if (node->p[j] && k- node->p[j]->x>0)
				k-=node->p[j]->x,lj=j;
			else if (node->p[j])
				break;
		if (j==10) j=lj;
		printf("%d",j);
		node= node->p[j];
	}
	printf("\n");
}

int main()
{
	int i,c,k;
	freopen(IN,"r",stdin);
	freopen(OUT,"w",stdout);
	
	scanf("%d",&N);
	
	for (i=0;i<N;++i)
	{
		scanf("%d",&c);
		switch(c)
		{
			case 1:
				scanf("%s",s);
				insert(s);
			break;
			case 0:
				scanf("%d",&k);
				Query(k);
			break;
		}
	}
	
	return 0;
}