Cod sursa(job #903056)

Utilizator aciobanusebiCiobanu Sebastian aciobanusebi Data 1 martie 2013 18:17:09
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include<cstdio>
#include<cstring>
using namespace std;
struct trie
{
    int cuv,ap;
    trie *N[26];
    trie ()
    {
        cuv=ap=0;
        for(int i=0;i<26;i++)
            N[i]=NULL;
    }
}*R,*Q,*st[30],*X;
void add(char s[])
{
    Q=R;
    for(int i=0;i<strlen(s);i++)
        {
            if(Q->N[s[i]-'a']==NULL)  Q->N[s[i]-'a']=new trie;
            Q->ap++;
            Q=Q->N[s[i]-'a'];
        }
    Q->ap++;
    Q->cuv++;
}
void remove(char s[])
{
    int i;
    Q=R;
    for(i=0;i<strlen(s);i++)
    {
        st[i]=Q;
        Q->ap--;
        Q=Q->N[s[i]-'a'];
    }
    st[i]=Q;
    Q->ap--;
    Q->cuv--;
    i=strlen(s)-1; //printf("%d\n",i);
    int j=strlen(s);
    while(st[j]->ap==0&&st[j]->cuv==0&&j)
    {
        X=st[j];
        st[j]=st[i]->N[s[i]-'a']=NULL;
        delete X;
        i--;
        j--;
    }
}
void aparitii(char s[])
{
    Q=R;
    for(int i=0;i<strlen(s);i++)
    {
        if(Q->N[s[i]-'a']==NULL)
            {
                printf("0\n");
                return;
            }
        Q=Q->N[s[i]-'a'];
    }
    printf("%d\n",Q->cuv);
}
void prefix(char s[])
{
    int i;
    Q=R;
    for(i=0;i<strlen(s);i++)
       {
           if(Q->N[s[i]-'a']==NULL) break;
            Q=Q->N[s[i]-'a'];
        }
    printf("%d\n",i);
}
void citire()
{
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    int x;
    char s[30];
    while(!feof(stdin))
    {
        scanf("%d",&x); //printf("%d ",x);
        scanf("%s",s);
        //printf("%d %s\n",x,s);
        if(!feof(stdin))
        if(x==0) add(s);
        else if(x==1) remove(s);
        else if(x==2) aparitii(s);
        else prefix(s);
    }
}
int main()
{
    R=new trie;
    citire();
    return 0;
}