Cod sursa(job #1707028)

Utilizator contnouAndrei Pavel contnou Data 24 mai 2016 00:53:23
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.15 kb
#include<fstream>
#include<iostream>
#include<string>
#include <sstream>

using namespace std;

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

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


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

	char first = word.at(0);

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

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

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

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

	return root;
}

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

	char first = word.at(0);
	word = word.substr(1);

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

int main() {
	//
	TrieNode root;

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

	string line;

	while (getline(f, line)) {
		int opType;
		string opValue;

		istringstream linestream(line);
		linestream >> opType >> opValue;

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