Cod sursa(job #2304315)

Utilizator Vlad3108Tir Vlad Ioan Vlad3108 Data 17 decembrie 2018 21:36:49
Problema Trie Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <bits/stdc++.h>
using namespace std;
/// nod
struct Trie{
    int ct,ct_son;
    Trie *son[26];
    Trie(){
        ct=ct_son=0;
        memset(son,0,sizeof(son));
    }
};
Trie *root=new Trie;
void insert(Trie *nod,char *s){
    if(*s==0){
        ++nod->ct;
        return ;
    }
    ++nod->ct_son;
    if(nod->son[*s-'a']==0)
        nod->son[*s-'a']=new Trie;
    insert(nod->son[*s-'a'],s+1);
}
bool erase(Trie *nod,char *s){
    if(*s==0)
        --nod->ct;
    else{
        --nod->ct_son;
        if(erase(nod->son[*s-'a'],s+1))
            nod->son[*s-'a']=0;
    }
    if(nod->ct==0&&nod->ct_son==0&&nod!=root){
        delete nod;
        return 1;
    }
    return 0;
}
int frequency(Trie *nod,char *s){
    if(*s==0)
        return nod->ct;
    else{
        if(nod->son[*s-'a']==0) return 0;
        else return frequency(nod->son[*s-'a'],s+1);
    }
}
int longest_common_prefix(Trie *nod,char *s){
    if(*s==0||nod->son[*s-'a']==0)
        return 0;
    return 1+longest_common_prefix(nod->son[*s-'a'],s+1);
}
int tip;
char s[20];
int main(){
    freopen("trie.in","r",stdin);
    freopen("trie.out","w",stdout);
    while(scanf("%d %s",&tip,s)!=EOF){
        if(tip==0) insert(root,s);
        else if(tip==1) erase(root,s);
        else if(tip==2) printf("%d\n",frequency(root,s));
        else printf("%d\n",longest_common_prefix(root,s));
    }
	return 0;
}