Cod sursa(job #672365)

Utilizator PetcuIoanPetcu Ioan Vlad PetcuIoan Data 1 februarie 2012 22:19:57
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.91 kb
#include<stdio.h>
#include<assert.h>
#include<string.h>
#include<algorithm>
#include<string>
#include<iostream>

using namespace std;

struct trie{
    int cnt,son;
    trie *sons[26];
    trie(){
        cnt=son=0;
        memset(sons,0,sizeof(sons));
    }
};

trie *t=new trie;

void update (trie *p,string s){
    if(s.size()==0){
        p->cnt++;
        return ;
    }
    if(p->sons[s[0]-'a']!=0)
        update(p->sons[s[0]-'a'],s.substr(1,s.size()-1));
    else{
        p->sons[s[0]-'a']=new trie;
        p->son++;
        update(p->sons[s[0]-'a'],s.substr(1,s.size()-1));
    }
}

int erase(trie *p,string s){
    if(s.size()==0){
        p->cnt--;
        if(p->cnt==0 && p->son==0){
            delete p;
            return 1;
        }
        return 0;
    }
    int x;
    x=erase(p->sons[s[0]-'a'],s.substr(1,s.size()-1));
    if(x)
    {
        p->sons[s[0]-'a']=0;
        p->son--;
    }
    if(x && p->son==0){
        delete p;
        return 1;
    }
    return 0;
}

int query(trie *p,string s){
    if(s.size()==0){
        return p->cnt;
    }
    if(p->sons[s[0]-'a']==0)
        return 0;
    return query(p->sons[s[0]-'a'],s.substr(1,s.size()-1));
}

int l_pref(trie *p,string s){
    if(s.size()==0)
        if(p->son>=1 || p->cnt>1)
            return 1;
        else
            return 0;
    int x=0;
    if(p->sons[s[0]-'a']!=0)
        x=l_pref(p->sons[s[0]-'a'],s.substr(1,s.size()-1));
    if(p->son>1)
        x=max(x,1);
    return x+1;
}

int main(){
    assert(freopen("trie.in","r",stdin)!=NULL);
    assert(freopen("trie.out","w",stdout)!=NULL);

    int op_type;
    string cuv;

    while(scanf("%d ",&op_type)!=EOF){
        cin >> cuv;
        if(op_type==0)
            update(t,cuv);
        else if(op_type==1)
            erase(t,cuv);
        else if(op_type==2)
            printf("%d\n",query(t,cuv));
        else if(op_type==3)
            printf("%d\n",l_pref(t,cuv)-1);
    }

    return 0;
}