Cod sursa(job #1122914)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 25 februarie 2014 21:19:08
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include<cstdio>
#include<cstring>
using namespace std;
int op,l,n; char s[25];
struct trie
{
    int cnt,was;
    trie *son[30];
    trie()
    {
        memset(son,0,sizeof(son));
        cnt=was=0;
    }
};
trie *root=new trie;
void ad(trie *t,int poz)
{
    if(poz==n) {t->cnt++; return;}
    l=s[poz]-'a';
    if(!t->son[l]) t->son[l]=new trie;
    t->son[l]->was++;
    ad(t->son[l],poz+1);
}
void st(trie *t,int poz)
{
    if(poz==n) {t->cnt--; return;}
    l=s[poz]-'a';
    t->son[l]->was--;
    st(t->son[l],poz+1);
}
void ap(trie *t,int poz)
{
    if(poz==n) {printf("%d\n",t->cnt); return;}
    l=s[poz]-'a';
    if(!t->son[l] || !t->son[l]->was) {printf("0\n"); return;}
    ap(t->son[l],poz+1);
}
void pr(trie *t,int poz)
{
    if(poz==n) {printf("%d\n",n); return;}
    l=s[poz]-'a';
    if(!t->son[l] || !t->son[l]->was) {printf("%d\n",poz); return;}
    pr(t->son[l],poz+1);
}
int main()
{
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);
	while(scanf("%d %s",&op,s)+1)
	{
	    n=strlen(s);
	    if(op==0) ad(root,0);
	    else if(op==1) st(root,0);
	    else if(op==2) ap(root,0);
	    else pr(root,0);
	}
	return 0;
}