Cod sursa(job #679038)

Utilizator bog29Antohi Bogdan bog29 Data 12 februarie 2012 18:06:50
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.98 kb
#include<fstream>
#define dmax 22
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");

class trieNode
{
public:
	int words;
	int prefixes;
	trieNode* next[26];
	trieNode();
};

trieNode::trieNode()
{
	words = 0;
	prefixes = 0;
	
	for(int i=0; i<26; i++)
		next[i] = NULL;
}	


void addWord(char* word, trieNode* trie)
{
	int length = strlen(word);
	
	for(int i=0; i<length; i++)
	{	
		int position = word[i] - 'a';
		
		if(trie->next[position] != NULL )
		{	
			trie = trie->next[position];
			trie->prefixes++;
		}
		else
		{	
			trie->next[position] = new trieNode();
			trie = trie->next[position];
			trie->prefixes++;
		}
		
	}	
	
	trie->words++;
}

void deleteWord(char* word, trieNode* trie)
{
	int length = strlen(word);
	
	for(int i=0; i<length; i++)
	{
		int position = word[i] - 'a';
		if(trie->next[position] != NULL)
			trie = trie->next[position];
		trie->prefixes--;	
	}
	
	trie->words--;
}	


void count(char* word, trieNode* trie)
{
	int length = strlen(word);
	
	for(int i=0; i<length; i++)
	{	
		int position = word[i] - 'a';
		if(trie->next[word[i] - 'a'] != NULL)
			trie = trie->next[position];
	}
	
	out<<trie->words<<'\n';
	
}	


void prefix(char* word, trieNode* trie)
{
	int length = strlen(word);
	
	int i=0;
	int position = word[0]-'a';
	
	while(i < length && trie->next[position] != NULL && trie->next[position]->prefixes != 0)
	{	if(trie->next[word[i]- 'a'] != NULL)
			trie = trie->next[word[i] - 'a'];
		i++;
		position = word[i]-'a';
	}	
	
	out<<i<<'\n';
}

int main()
{
	trieNode trie;
	
	while(!in.eof() )
	{
		int operation;
		char word[dmax];
		
		in>>operation>>word;
		
		if(operation == 0)
			addWord(word, &trie);
		else if(operation == 1)
		{	
			deleteWord(word, &trie);
		}
		else if(operation == 2)
			count(word, &trie);
		else if(operation == 3)
			prefix(word, &trie);
		operation = 4;
	}

	in.close();
	
	out.close();
	
	return 0;
}