Cod sursa(job #772363)

Utilizator realmchaos12Victor realmchaos12 Data 29 iulie 2012 12:49:51
Problema Trie Scor 55
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include<stdio.h>
#include<string.h>
#include<iostream>

using namespace std;

struct NodeTrie {
	int V;
	NodeTrie* ntr[28];
	NodeTrie() {
		V = 0;
		for(int i = 0; i < 26; i++)
			ntr[i] = 0;
	}
};

NodeTrie* rTrie;
void insertWordInTrie(NodeTrie* root, char* word, int len) {
	if(len == 0) {
		root->V++;
		return;
	}
	if(root->ntr[word[0]-'a'] == 0) {
		root->ntr[word[0]-'a'] = new NodeTrie();
	}
	insertWordInTrie(root->ntr[word[0]-'a'], word + 1, len - 1);
}
void deleteWordFromTrie(NodeTrie*& root, char* word, int len) {
	if(len == 0) {
		int k = 0;
		for(int i = 0; i < 26; i++)
		if(root->ntr[i] != 0) k++;
		root->V--;
		if(k == 0 && root -> V == 0) {
		  delete root;
		  root = 0;
		}
		return;
	}
	deleteWordFromTrie(root->ntr[word[0]-'a'], word + 1, len - 1);
	int k = 0;
	for(int i = 0; i < 26; i++)
	  if(root->ntr[i] != 0) k++;
	 if(k == 0) {
		delete root;
		root = 0;
	 }
}
int howManyInTrie(NodeTrie* root, char* word, int len) {
	if(root == 0) return 0;
	if(len == 0) return root->V;
	return howManyInTrie(root->ntr[word[0]-'a'], word + 1, len - 1);
}
int longestPrefix(NodeTrie* root, char* word, int len) {
	if(root == 0) return -1;
	if(len == 0) return 0;
	return 1 + longestPrefix(root->ntr[word[0]-'a'], word + 1, len - 1);
}
int main() {
	freopen("trie.in","r",stdin);
	freopen("trie.out","w",stdout);

	rTrie = new NodeTrie();
	int ps = 0;
	while(!feof(stdin)) {
		int codop;
		ps++;
		char word[25];
		scanf("%d %s",&codop, &word);
		if(feof(stdin)) break;
		int lung = strlen(word);
		if(codop == 0) {
			insertWordInTrie(rTrie, word, lung);
		}
		else
		 if(codop == 1) {
			 deleteWordFromTrie(rTrie, word, lung);
		 }
		 else
		  if(codop == 2) {
			   printf("%d\n",howManyInTrie(rTrie, word, lung));
		  }
		  else 
		   if(codop == 3) {
			   printf("%d\n",longestPrefix(rTrie, word, lung));
		   }
	}
	return 0;
}