Cod sursa(job #357271)

Utilizator undogSavu Victor Gabriel undog Data 18 octombrie 2009 17:42:58
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <cstdio>
#include <cstring>

struct node{
	node* l[26];
	int n;
};

node* root;

void add(char* w,int n){
	node* tmp=root;
	int i;
	for(i=0;i<n;i++){
		if(tmp->l[w[i]]==NULL){
			node* t=new node;
			t->n=0;
			for(int j=0;j<26;j++)
				t->l[j]=NULL;
			tmp->l[w[i]]=t;
		}
		tmp=tmp->l[w[i]];
	}
	tmp->n++;
}

void remove(char* w,int n){
	node* tmp=root;
	int i;
	for(i=0;i<n;i++)
		tmp=tmp->l[w[i]];
	tmp->n--;
	if(tmp->n==0){
		for(i=0;i<26;i++)
			if(tmp->l[i])
				break;
		if(i==26){
			tmp=root;
			for(i=0;i<n-1;i++)
				tmp=tmp->l[w[i]];
			delete tmp->l[w[i]];
			tmp->l[w[i]]=NULL;
		}
	}
}

int count(char* w,int n){
	node* tmp=root;
	int i;
	for(i=0;i<n;i++)
		if(tmp)
			tmp=tmp->l[w[i]];
		else
			return 0;
	return tmp->n;
}

int share(char* w,int n){
	node* tmp=root;
	int i,j,max=0;
	for(i=0;i<n&&tmp;i++){
		for(j=0;j<26;j++)
			if(tmp->l[j])
				break;
		if(j<26||tmp->n)
			max=i;
		tmp=tmp->l[w[i]];
	}
	return max;
}

int main(){
	freopen("trie.in","rt",stdin);
	freopen("trie.out","wt",stdout);

	int c,i,n;
	char w[50];
	
	node* t=new node;
	t->n=0;
	for(int j=0;j<26;j++)
	t->l[j]=NULL;
	
	root=t;
	
	while(!feof(stdin)){
		scanf("%d%s",&i,w);
		n=strlen(w);
		for(c=0;c<n;c++)
			w[c]-='a';
		switch(i){
			case 0: add(w,n);break;
			case 1: remove(w,n);break;
			case 2: printf("%d\n",count(w,n));break;
			case 3: printf("%d\n",share(w,n));break;
		}
	}
	return 0;
}