Cod sursa(job #674088)

Utilizator andunhillMacarescu Sebastian andunhill Data 5 februarie 2012 15:27:53
Problema Trie Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include<fstream>
using namespace std;

ifstream f("trie.in");
ofstream g("trie.out");

class trie
{	
	struct node
	{	int nr_prefix;
		int nr_word;
		node *sons[26];
		
		node()
		{	nr_prefix = nr_word = 0;
			
			for(int i = 0; i < 26; i++) sons[i] = NULL;
		}
	};
	
	node *root;
	
	public:
		
		trie()
		{	root = new node;
		}
		
		void R_push(char *str, node *p)
		{	if(*str == NULL) 
			{	p->nr_word++;
				return;
			}
			
			if(p->sons[*str - 97] == NULL)
			{	node *q = new node;
				q->nr_prefix++;
				p->sons[*str - 97] = q;
				R_push(str + 1, q);
			}
			else p->sons[*str - 97]->nr_prefix++, R_push(str + 1, p->sons[*str - 97]);
		}
		
		void R_pop(char *str, node *&p)
		{	if(*str == NULL && p->nr_prefix == 0) 
			{	delete p; p = NULL;
				return;
			}
			else if(*str == NULL)
			{	p->nr_word--;
				return;
			}
			
			p->sons[*str - 97]->nr_prefix--;
			R_pop(str + 1, p->sons[*str - 97]);
			
			if(p->sons[*str - 97] != NULL && p->sons[*str - 97]->nr_prefix == 0)
			{	delete p->sons[*str - 97];
				p->sons[*str - 97] = NULL;
			}
		}
		
		void push(char *str)
		{	R_push(str, root);
		}
		
		void pop(char *str)
		{	R_pop(str, root);
		}
		
		int count(char *str)
		{	node *p = root;
			while(*str)
			{	if(p->sons[*str - 97] == NULL) return p->nr_word;
				
				p = p->sons[*str - 97];
				str++;
			}
			return p->nr_word;
		}
		
		int long_com_pref(char *str)
		{	int longest = 0;
			node *p = root;
			
			while(*str)
			{	if(p->sons[*str - 97] == NULL) return longest;
				
				p = p->sons[*str - 97];
				longest++;
				str++;
			}
			return longest;
		}
};

trie A;

int main()
{	int op;
	char word[21];
	
	while(f>>op>>word)
	{	//f>>op>>word;
		
		switch(op)
		{	case 0:	A.push(word); break;
			case 1:	A.pop(word); break;
			case 2:	g<<A.count(word)<<'\n'; break;
			case 3:	g<<A.long_com_pref(word)<<'\n'; break;
		}
	}
	
	f.close();
	g.close();
	return 0;
}