Cod sursa(job #470566)

Utilizator dushmiMihai-Alexandru Dusmanu dushmi Data 14 iulie 2010 16:55:41
Problema Nums Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.51 kb
#include<cstdio>
#include<cstring>
#define L 1<<17
int max,pc,pp,lung,poz,POZ;
bool ok;
char str[L];
struct Nod
{
    int nrcuv;
    Nod *f[10];
    Nod()
    {
        for(int i=0;i<10;i++)
            f[i]=NULL;
        nrcuv=0;
    }
};
void init()
{
    int poz,x,n,lung;
    char s[L];
    freopen("nums.in","r",stdin);
    freopen("nums.out","w",stdout);
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d ",&x);
        if(x==1)
        {
            scanf("%s\n",&s);
            lung=strlen(s);
            if(lung>max)
                max=lung;
        }
        else scanf("%d",&poz);
    }
    fclose(stdin);
}
void insert(Nod *nod)
{
    ++nod->nrcuv;
    if(poz==lung)
        return;
    if(pc+lung<max)
    {
        pc++;
        if(nod->f[0])
        {
            insert(nod->f[0]);
            return;
        }
        nod->f[0]=new Nod();
        insert(nod->f[0]);
        return;
    }
    int cor=str[poz]-'0';
    if(nod->f[cor])
    {
		++poz;
        insert(nod->f[cor]);
        return;
    }
    nod->f[cor]=new Nod();
	++poz;
    insert(nod->f[cor]);
}
void check(Nod *nod)
{
    for(int i=0;i<10;i++)
        if(nod->f[i])
        {
            if(pp+(nod->f[i]->nrcuv)<POZ)
            {
                pp+=nod->f[i]->nrcuv;
                continue;
            }
            if(i)
                ok=true;
            if(ok==true)
                printf("%d",i);
            check(nod->f[i]);
            return;
        }
}
bool verif(Nod *nod)
{
    if(poz==lung)
        return true;
    if(pc+lung<max)
    {
        pc++;
        if(nod->f[0])
            return verif(nod->f[0]);
        return false;
    }
    int cor=str[poz]-'0';
    if(nod->f[cor])
	{
		poz++;
        return verif(nod->f[cor]);
	}
    return false;
}
void read()
{
    int x,n;
    freopen("nums.in","r",stdin);
    scanf("%d",&n);
    Nod *first=new Nod();
    for(int i=1;i<=n;i++)
    {
        scanf("%d ",&x);
        if(x==1)
        {
            scanf("%s\n",&str);
            lung=strlen(str);
			poz=0;
            pc=0;
            if(!verif(first))
            {
                pc=0;
				poz=0;
                insert(first);
            }
        }
        else
        {
            scanf("%d",&POZ);
            pp=0;
            ok=false;
            check(first);
            printf("\n");
        }
    }
    fclose(stdin);
}
int main()
{
    init();
    read();
    return 0;
}