Cod sursa(job #664665)

Utilizator CBogdanCiobanu Bogdan CBogdan Data 20 ianuarie 2012 17:13:09
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include<cstdio>
using namespace std;
struct node{
	int inf,nosoons;
	node *soons[27];
	node()
	{
		inf=0;nosoons=0;
		for(int i=0;i<=26;i++)
			soons[i]=0;
	}
}*root;

int type,del(node *curr,char *c),number(node *curr,char *c),prefix(node *curr,char *c,int);
char word[30];

void read(),solve(),insert(node *curr,char *c);

int main()
{
	solve();
	
	return 0;
}

void solve()
{
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);
	root=new node;
	while(1)
	{
		if(scanf("%d",&type)==-1)break;
		scanf("%s",word);
		if(type==0)insert(root,word);
		if(type==1)del(root,word);
		if(type==2)printf("%d\n",number(root,word));
		if(type==3)printf("%d\n",prefix(root,word,0));
	}
}

void insert(node *curr,char *c)
{
	if(!*c)
	{
		curr->inf++;
		return;
	}
	int k=*c-'a';
	if(!curr->soons[k])
	{
		curr->soons[k]=new node;
		curr->nosoons++;
	}
	insert(curr->soons[k],c+1);
}
int del(node *curr,char *c)
{
	int k=*c-'a';
	if(!*c)
	{
		curr->inf--;
	}
	else if(del(curr->soons[k],c+1))
	{
		curr->nosoons--;
		curr->soons[k]=0;
	}
	if(curr->inf==0 && curr->nosoons==0 && curr!=root)
	{
		delete curr;return 1;
	}
	return 0;
}
int number(node *curr,char *c)
{
	if(!*c)
		return curr->inf;
	int k=*c-'a';
	return(number(curr->soons[k],c+1));
	return 0;
}
int prefix(node *curr,char *c,int sol)
{
	int k=*c-'a';
	if(!(*c) || curr->soons[k]==0)return sol;
	return(prefix(curr->soons[k],(c+1),(sol+1)));
}