Cod sursa(job #1317076)

Utilizator heracleRadu Muntean heracle Data 14 ianuarie 2015 15:29:01
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
#include <cstdio>
#include <cstring>

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

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;
            p=NULL;
        }
        return p;
    }
    p->part--;

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

    if(p->term==0 && p->part==0)
    {
        delete p;
        p=NULL;
    }
    return p;

    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;

    int act,aux;

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

        if(x==0)
        {
            start=add(start,v);
        }
        if(x==1)
        {
            start=del(start,v);
        }
        if(x==2)
        {
            act=ask1(start,v);

//            fscanf(ver,"%d",&aux);

            //if(act!=aux)
            //{
            //    act=ask1(start,v);

            //}

            fprintf(out,"%d\n",act);
        }
        if(x==3)
        {
            act=ask2(start,v);

          //  fscanf(ver,"%d",&aux);

          //  if(act!=aux)
          //  {
          //      act=ask2(start,v);
          //  }

            fprintf(out,"%d\n",act);
        }
    }

    return 0;
}