Cod sursa(job #1427105)

Utilizator gabi.cristacheGabi Cristache gabi.cristache Data 1 mai 2015 15:39:13
Problema Trie Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

using namespace std;

class Node {
public:
	vector<Node *> neighbours;
	int freq, branches;

	Node() : neighbours(26, NULL), freq(0), branches(0) {}
	~Node() {}

	void insert(string word) {
		if (word == "") {
			++freq;
			return;
		}

		int index = word[0] - 'a';
		if (neighbours[index] == NULL) {
			neighbours[index] = new Node();
			++branches;
		}
			
		word.erase(0, 1);
		neighbours[index]->insert(word);
	}

	bool remove(string word) {
		int index = word[0] - 'a';
		
		if (word == "") {
			--freq;
		} else if (neighbours[index] != NULL) {
			word.erase(0, 1);	
	
			if (neighbours[index]->remove(word)) {

				delete neighbours[index];
				neighbours[index] = NULL;
				--branches;
			}
		} else {
			return false;
		}

		return freq == 0 && branches == 0;
	}

	int frequency(string word) {
		if (word == "") {
			return freq;
		}

		int index = word[0] - 'a';
		if (neighbours[index] != NULL) {
			word.erase(0, 1);
			return neighbours[index]->frequency(word);
		} else {
			return 0;
		}
	}

	int longestPrefix(string word, int length) {
		if (word == "" || neighbours[word[0] - 'a'] == NULL)
			return length;
	
		int index = word[0] - 'a';	
		word.erase(0, 1);
		return neighbours[index]->longestPrefix(word, length + 1);	
	}
};

ifstream fin("trie.in");
ofstream fout("trie.out");

Node * root;
string word;
int op;

int main() {
	root = new Node();

	while (true) {
		fin >> op >> word;
		if (fin.eof())
			break;

		if (op == 0) {
			root->insert(word);
		} else if (op == 1) {
			root->remove(word);
		} else if (op == 2) {
			fout << root->frequency(word) << '\n';
		} else if (op == 3) {
			fout << root->longestPrefix(word, 0) << '\n';
		}
	}

	return 0;
}