Cod sursa(job #1081916)

Utilizator iarbaCrestez Paul iarba Data 13 ianuarie 2014 22:49:05
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.85 kb
#include <cstdio>
#include <cstring>
#define free freee
//serios? sigh
using namespace std;
int st[10001],sf[10001],v[10001],q[10001],next[10001],atins[10001],k,p,free=1,caz;char s[22],maxx;
void add(int nod,int poz)
{
	atins[nod]++;
	if(poz==k){q[nod]++;return;}
	p=st[nod];while((v[p]!=s[poz]-'a')&&(p)){p=next[p];}
	if(p!=0){add(p,poz+1);}
	else{
		if(st[nod]==0){
			st[nod]=free;sf[nod]=free;v[free]=s[poz]-'a';next[free]=0;
					  }
		else{
			next[sf[nod]]=free;sf[nod]=free;v[free]=s[poz]-'a';next[free]=0;
			}
		p=free++;add(p,poz+1);
		}
}
void remove(int nod,int poz)
{
	atins[nod]--;
	if(poz==k){q[nod]--;return;}
	p=st[nod];while((v[p]!=s[poz]-'a')&&(p)){p=next[p];}
	if(p!=0){remove(p,poz+1);}
	else{
		if(st[nod]==0){
			st[nod]=free;sf[nod]=free;v[free]=s[poz]-'a';next[free]=0;
					  }
		else{
			next[sf[nod]]=free;sf[nod]=free;v[free]=s[poz]-'a';next[free]=0;
			}
		p=free++;remove(p,poz+1);
		}
}
void count(int nod,int poz)
{
	if(poz==k){printf("%d\n",q[nod]);return;}
	p=st[nod];while((v[p]!=s[poz]-'a')&&(p)){p=next[p];}
	if(p!=0){count(p,poz+1);}
	else{
		if(st[nod]==0){
			st[nod]=free;sf[nod]=free;v[free]=s[poz]-'a';next[free]=0;
					  }
		else{
			next[sf[nod]]=free;sf[nod]=free;v[free]=s[poz]-'a';next[free]=0;
			}
		p=free++;count(p,poz+1);
		}
}void lcp(int nod,int poz)
{
	p=st[nod];while((v[p]!=s[poz]-'a')&&(p)){p=next[p];}
	if(p!=0){
		if(atins[p]){maxx=poz;}else{printf("%ld\n",maxx+1);return;}
		lcp(p,poz+1);
			}
	else{
		printf("%ld\n",maxx+1);
		}
}
int main()
{
	v[0]=-1;
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);
	while(!feof(stdin)){
		scanf("%d %s\n",&caz,s);
		k=strlen(s);
		if(caz==0){add(0,0);}
		if(caz==1){remove(0,0);}
		if(caz==2){count(0,0);}
		if(caz==3){maxx=0;lcp(0,0);}
		for(caz=0;caz<k;caz++){s[caz]=0;}
								}
return 0;
}