Cod sursa(job #302008)

Utilizator c_iulyanCretu Iulian c_iulyan Data 8 aprilie 2009 16:35:30
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.24 kb
#include<cstdio>
#include<algorithm>
using namespace std;

struct trie
{
long k,fii;
char c;
trie *f[27];
trie()
	{
	k=fii=0;
	c=0;
	memset(f,0,sizeof(f));
	}
};

trie *T=new trie;
char b[1000];

void add(char *a,trie *t)
{
if(a[0]==0)
	{
	t->k++;
	return;
	}

if(!t->f[a[0]-97])
	{
	t->fii++;
	t->f[a[0]-97]=new trie;
	t->f[a[0]-97]->c=a[0];
	}
	
add(a+1,t->f[a[0]-97]);
}

bool del(char *a,trie *t)
{
if(a[0]==0)
	{
	t->k--;
	return !t->k&&!t->fii;
	}

if(del(a+1,t->f[a[0]-97]))
	{
	t->fii--;
	delete t->f[a[0]-97];
	t->f[a[0]-97]=0;
	return !t->fii&&!t->k;
	}
	
return 0;
}

long nrap(char *a,trie *t)
{
if(!t)
	return 0;
if(a[0]==0)
	return t->k;
	
return nrap(a+1,t->f[a[0]-97]);
}

long pref(char *a,trie *t)
{
if(a[0]==0||!t->f[a[0]-97]) return 0;

long x=(t->fii!=0?a-b+1:0);
return max(x,pref(a+1,t->f[a[0]-97]));
}

void go()
{
int x;
scanf("%d%s",&x,b);
while(!feof(stdin))
	{
	switch(x)
		{
		case 0: add(b,T);break;
		case 1: del(b,T);break;
		case 2: printf("%ld\n",nrap(b,T));break;
		case 3: printf("%ld\n",pref(b,T));break;
		}
	scanf("%d%s",&x,b);
	}
}

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

go();

return 0;
}