Cod sursa(job #1958301)

Utilizator RaduGiucleaGiuclea Radu RaduGiuclea Data 8 aprilie 2017 11:29:15
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <cstdio>
#include <cstring>
using namespace std;
struct nod
{
    int pref,nr;
    nod *nxt[26];
    nod()
    {
        pref=0;
        nr=0;
        for(int i=0;i<26;i++)
            nxt[i]=0;
    }
} *rad;
char cuv[30];
int prefix(nod *act,char v[])
{
    if(act==NULL)
        return -1;
    if(v[0]==0)
        return 0;
    return 1+prefix(act->nxt[v[0]-'a'],v+1);
}
int app( nod *act, char v[])
{
    if(act==NULL)
        return 0;
    if(v[0]==0)
        return act->nr;
    return app(act->nxt[v[0]-'a'],v+1);
}
nod *erase(nod *act,char v[])
{
    act->pref--;
    if(v[0]==0)
    {
        act->nr--;
        if(act->pref==0)
        {
            delete act;
            act=NULL;
        }
        return act;
    }
    act->nxt[v[0]-'a']=erase(act->nxt[v[0]-'a'],v+1);
    if(act->pref==0)
    {
        delete act;
        act=NULL;
    }
    return act;
}
nod *insert(nod *act, char v[])
{
    if(act==0)
    {
        act=new nod;
    }
    act->pref++;
    if(v[0]==0)
    {
        act->nr++;
        return act;
    }
    act->nxt[v[0]-'a']=insert(act->nxt[v[0]-'a'],v+1);
    return act;
}
int main()
{
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    int t;
    char a;
    while(scanf("%d%c",&t,&a)!=-1)
    {
        gets(cuv);
        if(t==0)
        rad=insert(rad,cuv);
        if(t==1)
        rad=erase(rad,cuv);
        if(t==2)
            printf("%d\n",app(rad,cuv));
        if(t==3)
            printf("%d\n",prefix(rad,cuv));
    }
    return 0;
}