Cod sursa(job #1314081)

Utilizator heracleRadu Muntean heracle Data 11 ianuarie 2015 15:10:11
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
#include <cstdio>
#include <cstring>

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

const int Q=25,INF=-200000;

char v[Q];

struct nod
{
    nod *fii[26];
    int term;
    int part;
    nod()
    {
        term=0;
        part=0;
        memset(fii,0,26);
    }
};

int ask2(nod *p, char v[])
{

    if(p==NULL)
    {
        return -1;
    }

    if(v[0]==0 || v[0]=='\n')
    {
        return 0;
    }

    return 1+ask2(p->fii[v[0]-'a'],v+1);
}

int ask1(nod *p, char v[])
{
    if(p==NULL)
        return 0;

    if(v[0]==0 || v[0]=='\n')
    {
        return p->term;
    }

    return ask1(p->fii[v[0]-'a'],v+1);
}

nod *del(nod *p, char v[])
{
    if(v[0]==0 || v[0]=='\n')
    {
        p->term--;
        if(p->term==0 && p->part==0)
        {
            delete p;
            return NULL;
        }
        return p;
    }
    p->part--;

    p->fii[v[0]-'a']=del(p->fii[v[0]-'a'],v+1);

    return p;
}

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

    if(v[0]==0 || v[0]=='\n')
    {
        p->term++;
        return p;
    }
    p->part++;

    p->fii[v[0]-'a']=add(p->fii[v[0]-'a'],v+1);

    return p;
}

int main()
{
    int x;

    nod *start=new nod;

    while(fscanf(in,"%d ",&x)==1)
    {
        fgets(v,Q,in);

        if(x==0)
        {
            add(start,v);
        }
        if(x==1)
        {
            del(start,v);
        }
        if(x==2)
        {
            fprintf(out,"%d\n",ask1(start,v));
        }
        if(x==3)
        {
            fprintf(out,"%d\n",ask2(start,v));
        }
    }

    return 0;
}