Cod sursa(job #1534512)

Utilizator heracleRadu Muntean heracle Data 23 noiembrie 2015 19:34:49
Problema Nums Scor 5
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.92 kb
#include <cstdio>
#include <map>

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

struct trie
{
//	trie *nxt[10];
	std::map<long long, trie*> nxt;
	int nrtot;
	trie()
	{
		nrtot=0;
	}
} *rad[100007];

char input[(6<<20)+29999];
int n;
int p=0;
char aux[100007];

bool adaos;

trie *add(trie *nod, char v[])
{
	if(nod==NULL)
		nod=new trie;

	long long act=0;

	if(v[0]==-1)
	{
		if(nod->nrtot==0)
		{
			nod->nrtot++;
			adaos=1;
		}
		else
			adaos=0;
		return nod;
	}
	for(int i=0; i<17; i++)
	{
		act=act*10+v[i];
	}

	nod->nxt[act]=add(nod->nxt[act],v+17);
	nod->nrtot+=adaos;

	return nod;
}

int aib[130007];

int ask(int &x)
{
	int pst=0,pow=1<<16;

	while(pow)
	{
		if(aib[pow+pst]<x)
		{
			pst+=pow;
			x-=aib[pst];
		}
		pow/=2;
	}
	return pst+1;
}

void update(int poz, int val)
{
	while(poz<130007)
	{
		aib[poz]+=val;
		poz+=poz&(-poz);
	}
}

int contor;

void baga(long long a)
{
	if(a<10)
	{
		aux[++contor]=a+'0';
		return;
	}
	baga(a/10);
	aux[++contor]=a%10+'0';
}

void afis(trie *nod, int nr)
{
	std::map<long long, trie*>::iterator it;

	for(it=nod->nxt.begin(); it!=nod->nxt.end(); it++)
	{
		if(it->second->nrtot<nr)
		{
			nr-=it->second->nrtot;
		}
		else
		{
			baga(it->first);
			afis(it->second,nr);
			return;
		}
	}
}

int main()
{
	fscanf(in,"%d",&n);
    fread(input,6<<20,1,in);

	int act;
	int ax;
    for(int i=1; i<=n; i++)
    {
		p++;
		if(input[p]=='0')
		{
			p+=2;
			act=0;
			while(input[p]!='\n')
			{
				act=act*10+input[p]-'0';
				p++;
			}

			ax=ask(act);
			contor=0;
			afis(rad[ax],act);
			aux[ax+1]=0;
			fputs(aux+1,out);
			fprintf(out,"\n");
		}
		else
		{
			p+=2;

			act=0;
			while(input[p]!='\n')
			{
				aux[act]=input[p]-'0';
				p++;
				act++;
			}

			for(int k=0; k<=30; k++)
				aux[act+k]=0;

			aux[act-act%17+17]=-1;

			if(rad[act])
				ax=rad[act]->nrtot;
			else
				ax=0;
			rad[act]=add(rad[act],aux);

			update(act, rad[act]->nrtot-ax);
		}
    }

    return 0;
}