Cod sursa(job #1212621)

Utilizator andreas.chelsauAndreas Chelsau andreas.chelsau Data 25 iulie 2014 13:25:27
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.7 kb
#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
typedef unsigned int uint;

struct TrieNode{
	bool fullWord;
	int wordNumber;
	TrieNode *links[26];
};

TrieNode* createInstance(){
	TrieNode *node = new TrieNode;
	node->fullWord = false;
	node->wordNumber = 0;
	for(int i = 0; i < 26; i++)
		node->links[i] = NULL;
	return node;
}
void add(TrieNode* root,string w){
	TrieNode* current = root;
	int offset = 97;
	for(uint i = 0; i < w.size(); i++){
		if(current->links[w[i] - offset] == NULL)	
			current->links[w[i] - offset] = createInstance();				
		current = current->links[w[i] - offset];
		current->wordNumber++;
	}
	current->fullWord = true;
}
bool children(TrieNode* root){
	int no = 0;
	for(int i = 0; i < 26; i++)
		if(root->links[i] != NULL)
			no++;
	if(no > 1)
		return true;
	return false;

}
void print(TrieNode* root, char branch[],int level){
	if(root->fullWord == true){
		for(int i = 0; i < level;i++)
			cout<<branch[i];
		cout<<'\n';
	}
	for(int i = 0; i < 26; i++){
		if(root->links[i] != NULL){
			branch[level] = i + 'a';
			print(root->links[i],branch,level + 1);
		}
	}
}
int findWord(TrieNode *root,string word){

	for(uint i = 0; i < word.size(); i++){
		if(root->links[word[i] - 'a'] != NULL)
			root = root->links[word[i] - 'a'];
		else
			return 0;
	}
	if(root->fullWord)
		return root->wordNumber;
	return 0;
}
int longestPrefix(TrieNode *root,string word){
	int maxim = 0;
	for(uint i = 0; i < word.size(); i++){
		if(root->links[word[i] - 'a'] != NULL){
			root = root->links[word[i] - 'a'];
			maxim++;
		}
		else
			break;
	}
	return maxim;
}
void deleteWord(TrieNode *root, string w,uint index){
	if(index < w.size()){
		deleteWord(root->links[w[index] - 'a'],w,index + 1);

		if(index < w.size()){
			if(root->links[w[index] - 'a']->wordNumber > 1)
				root->links[w[index] - 'a']->wordNumber--;
			else{
				free(root->links[w[index] - 'a']);
				root->links[w[index] - 'a'] = NULL;
			}
		
		}
	
	}
}
int main(){
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);
	string str;
	TrieNode* root = createInstance();
	
	while(getline(cin,str)){
		if(str[0] == '0'){
			str = str.substr(2,str.size());
			add(root,str);
		}
		if(str[0] == '1'){
			str = str.substr(2,str.size());
			deleteWord(root,str,0);
		//	char branch[20];
		//	print(root,branch,0);
		}
		if(str[0] == '2'){
			str = str.substr(2,str.size());
		//	char branch[20];
		//	print(root,branch,0);
			cout<<findWord(root,str)<<'\n';
		}
		if(str[0] == '3'){
			str = str.substr(2,str.size());
		//	char branch[20];
		//	print(root,branch,0);
			cout<<longestPrefix(root,str)<<'\n';
		}
	}
	return 0;
}