Cod sursa(job #1162825)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 31 martie 2014 23:44:07
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include<cstdio>
#include<cstring>
using namespace std;
int i,n,l; char s[25];
struct trie
{
    int was,count;
    trie *f[26];
    trie()
    {
        was=count=0;
        memset(f,0,sizeof(f));
    }
};
trie *root=new trie;
void a(trie *t,int poz)
{
    if(poz==n) {t->count++; return;}
    l=s[poz]-'a';
    if(!t->f[l]) t->f[l]=new trie;
    t->f[l]->was++;
    a(t->f[l],poz+1);
}
void e(trie *t,int poz)
{
    if(poz==n) {t->count--; return;}
    l=s[poz]-'a';
    t->f[l]->was--;
    e(t->f[l],poz+1);
}
void c(trie *t,int poz)
{
    if(poz==n) {printf("%d\n",t->count); return;}
    l=s[poz]-'a';
    if(!t->f[l] || !t->f[l]->was) {printf("0\n"); return;}
    c(t->f[l],poz+1);
}
void p(trie *t,int poz)
{
    if(poz==n) {printf("%d\n",n); return;}
    l=s[poz]-'a';
    if(!t->f[l] || !t->f[l]->was) {printf("%d\n",poz); return;}
    p(t->f[l],poz+1);
}
int main()
{
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);
	while(scanf("%d %s",&i,s)+1)
	{
	    n=strlen(s);
	    if(i==0) a(root,0);
	    else if(i==1) e(root,0);
	    else if(i==2) c(root,0);
	    else p(root,0);
	}
	return 0;
}