Cod sursa(job #1519710)

Utilizator avaspAva Spataru avasp Data 7 noiembrie 2015 18:55:47
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include<cstdio>
using namespace std;
int tip;
char s[21];
struct Trie{
    int cnt,nrson;
    Trie *son[27];
    Trie(){
        nrson=0;
        cnt=0;
        for(int i=0;i<=26;i++)
            son[i]=NULL;
    }
};
Trie *T;

void add(Trie *node, char *s){
    if(*s==NULL){
        node->cnt++;
        return;
    }
    if(node->son[s[0]-'a']==NULL){
        node->nrson++;
        node->son[s[0]-'a']=new Trie;
    }
    add(node->son[s[0]-'a'],s+1);
}

int count(Trie *node, char *s){
    if(*s==NULL){
        return node->cnt;
    }
    if(node->son[s[0]-'a']==NULL)
        return 0;
    return count(node->son[s[0]-'a'],s+1);
}

bool remove(Trie *node, char *s){
    if(*s==NULL){
        node->cnt--;
        if(node!=T&&node->nrson==0&&node->cnt==0){
            delete node;
            return 1;
        }
        return 0;
    }
    if(remove(node->son[s[0]-'a'],s+1)==1){
        node->nrson--;
        node->son[s[0]-'a']=NULL;
    }
    if(node!=T&&node->nrson==0&&node->cnt==0){
        delete node;
        return 1;
    }
    return 0;
}

int pref(Trie *node, char *s){
    if(*s==NULL||node->son[s[0]-'a']==NULL){
        return 0;
    }
    return 1+pref(node->son[s[0]-'a'],s+1);
}

int main(){
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    T=new Trie;
    while(scanf("%d %s",&tip,&s)!=EOF){
        if(tip==0)
            add(T,s);
        else
        if(tip==1)
            remove(T,s);
        else
        if(tip==2)
            printf("%d\n",count(T,s));
        else
           printf("%d\n", pref(T,s));
        int x;
        x=1;
    }
    return 0;
}