Cod sursa(job #521296)

Utilizator crushackPopescu Silviu crushack Data 11 ianuarie 2011 23:27:44
Problema Nums Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.62 kb
#include <stdio.h>
#include <string.h>
#define NMax 100005
#define zeros(x) ( (x^(x-1))&x )
const char IN[]="nums.in",OUT[]="nums.out";

int N;
char s[NMax];

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

nod **root = new nod*[NMax];

void Init()
{
	int i;
	for (i=0;i<NMax;++i)
		root[i]=new nod;
}

void Insert(char *s)
{
	int c=0,i,L=strlen(s);
	if (!root[L]) root[L]=new nod;
	nod* node = root[ L ];
	
	for (i=0;s[i];++i)
	{
		if (!node->a[ s[i]-'0'])
		{
			node->a[ s[i] - '0']=new nod;
			++c;
		}
		node= node->a[ s[i]-'0'];
	}
	node=root[L];
	if(c>0){
		++node->x;
		for (i=0;s[i];++i)
		{
			node= node->a[ s[i]-'0'];
			++node->x;
		}
	}
}

void Query(int k)
{
	int i,finish=false;
	for (i=0;i<NMax && ( !root[i]->x || k-root[i]->x>0 );++i)
		if (root[i]) k-=root[i]->x;
	nod *node = root[i];
	while (k>0 && node->x!=1)
	{
		for (i=0;i<10;++i)
			if ( node->a[i] && k-node->a[i]->x>0)
				k-=node->a[i]->x;
			else if ( node->a[i] )
				break;
		if (i>=10) i=9;
		printf("%d",i);
		node=node->a[i];
	}
	while (!finish)
	{
		for (i=0;i<10;++i)
			if (node->a[i])
				break;
		if (i<10)
		{
			printf("%d",i);
			node=node->a[i];
		}
		else
			finish=true;
	}
	printf("\n");
}

int main()
{
	int i,c,k;
	freopen(IN,"r",stdin);
	freopen(OUT,"w",stdout);
	scanf("%d",&N);
	
	Init();
	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;
		}
	}
	fclose(stdin);fclose(stdout);
	return 0;
}