Cod sursa(job #470562)

Utilizator dushmiMihai-Alexandru Dusmanu dushmi Data 14 iulie 2010 16:26:46
Problema Nums Scor 25
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.14 kb
#include<cstdio>
#include<cstring>
#define L 1<<17
int max,pc,pp;
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,int lung,int poz)
{
    ++nod->nrcuv;
    if(poz==lung)
        return;
    if(pc+lung<max)
    {
        pc++;
        if(nod->f[0])
        {
            insert(nod->f[0],lung,poz);
            return;
        }
        nod->f[0]=new Nod();
        insert(nod->f[0],lung,poz);
        return;
    }
    int cor=str[poz]-'0';
    if(nod->f[cor])
    {
        insert(nod->f[cor],lung,poz+1);
        return;
    }
    nod->f[cor]=new Nod();
    insert(nod->f[cor],lung,poz+1);
}
void check(Nod *nod,int poz)
{
    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],poz);
            return;
        }
}
void read()
{
    int poz,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);
            int lung=strlen(str);
            pc=0;
            insert(first,lung,0);
        }
        else
        {
            scanf("%d",&poz);
            pp=0;
            ok=false;
            check(first,poz);
            printf("\n");
        }
    }
    fclose(stdin);
}
int main()
{
    init();
    read();
    return 0;
}