Cod sursa(job #655222)

Utilizator rootsroots1 roots Data 1 ianuarie 2012 20:36:41
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <stdio.h>

#define ind (*w-'a')

#define wL 25

struct trie
{
    int nod;
    trie *link[26];

    trie()
    {
        nod=0;
        for(int i=0;i<26;++i) link[i]=NULL;
    }
}*t=new trie;

int count;

inline void addw(trie *t,char *w)
{
    if(*w=='\n')
    {
        ++t->nod;
        return;
    }

    if(t->link[ind]==NULL)
        t->link[ind]=new trie;

    addw(t->link[ind],w+1);
}

inline void delw(trie *t,char *w)
{
    if(*w=='\n')
    {
        --t->nod;
        if(t->nod==0) delete t->link[ind];
        return;
    }

    delw(t->link[ind],w+1);
    if(t->link[ind]==NULL) delete t->link[ind];
}

inline int cntw(trie *t,char *w)
{
    if(*w=='\n') return t->nod;

    if(t->link[ind]) return cntw(t->link[ind],w+1);
    else return 0;
}

inline int prew(trie *t,char *w)
{
    if(*w=='\n') return count;

    int ok=0;
    for(int i=0;i<26;++i)
        if(t->link[i]&&i!=ind)
        {
            ++ok;
            break;
        }

    if(ok&&t->link[ind])
    {
        ++count;
        return prew(t->link[ind],w+1);
    }
    else return count;
}

int main()
{
    int x;
    char w[wL];

    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);

    while(!feof(stdin))
    {
        scanf("%d ",&x);
        fgets(w,wL,stdin);

        if(!feof(stdin))
        {
            if(x==0) { addw(t,w); continue; }
            if(x==1) { delw(t,w); continue; }
            if(x==2) { printf("%d\n",cntw(t,w)); continue; }
            count=0;
            printf("%d\n",prew(t,w)+1);
        }
    }

    return 0;
}