Cod sursa(job #1707036)

Utilizator contnouAndrei Pavel contnou Data 24 mai 2016 01:22:44
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 2.03 kb
#include<fstream>
#include<iostream>
#include<string>
#include<cstring>
#include <sstream>


using namespace std;
string word;

struct TrieNode {
	int count;
	int childrenCount;
	TrieNode* children[28]; 

	TrieNode() {
		count = 0;
		childrenCount = 0;
		memset(children, 0, sizeof(children));
	}
};


void addWord(TrieNode* root, int pos) {
	//
	if (word.length() == pos + 1) {
		root->count++;
		return;
	}

	char first = word.at(pos);

	if (!root->children[first - 'a']) {
		root->childrenCount++;
		root->children[first - 'a'] = new TrieNode();
	}
	
	addWord(root->children[first - 'a'], pos + 1);
}

int queryWordCount(TrieNode* root, int pos) {
	//
	if (word.length() == pos + 1) {
		return root->count;
	}

	char first = word.at(pos);
	
	if (root->children[first - 'a']) {
		return queryWordCount(root->children[first - 'a'], pos + 1);
	} else {
		return 0;
	}
}

TrieNode* deleteWord(TrieNode* root, int pos) {
	//
	if (word.length() == pos + 1) {
		root->count--;
	} else {
		char first = word.at(pos);
		
		root->children[first - 'a'] = deleteWord(root->children[first - 'a'], pos + 1);
		if (!root->children[first - 'a']) {
			root->childrenCount--;
		}
	}
	
	if (root->childrenCount == 0 && root->count == 0) {
		delete root;
		return 0;
	}

	return root;
}

int queryLongestPrefix(TrieNode *root, int pos) {
	//
	if (word.length() == pos + 1) {
		return 0;
	}

	char first = word.at(pos);

	if (root && root->children[first-'a']) {
		return 1 + queryLongestPrefix(root->children[first-'a'], pos + 1);
	} else {
		return 0;
	}
	
}

int main() {
	//
	TrieNode root;

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

	string line;
	int opType;

	while (f >> opType) {
		string opValue;
		f >> word;

		switch (opType) {
			case 0:
				addWord(&root, 0);
				break;
			case 1:
				deleteWord(&root, 0);
				break;
			case 2:
				g << queryWordCount(&root, 0) << "\n"; 
				break;
			case 3:
				g << queryLongestPrefix(&root, 0) << "\n";
		}
	}
}