Cod sursa(job #1308115)

Utilizator whoasdas dasdas who Data 3 ianuarie 2015 16:30:57
Problema Trie Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#define IA_PROB "trie"


#include <string>
#include <vector>
#include <set>
#include <map>
#include <unordered_map>
#include <queue>
#include <stack>

#include <algorithm>

#include <fstream>
#include <iostream>

using namespace std;


class Trie {
private:
	struct node {
		int refcnt;
		unordered_map<char, node*> children;
		node() : refcnt(0), children() { }
	} root;

	void _remove(node *n, string &word, int i) {
		n->refcnt--;
		if (i < word.size()) {
			node *child = n->children[word[i]];
			_remove(child, word, i + 1);
			if (child->refcnt == 0) {
				n->children.erase(word[i]);
				delete child;
			}
		}
	}
public:
	void insert(string &word) {
		node *n = &root;
		n->refcnt++;
		word.push_back('#');
		for (char c : word) {
			if (n->children.count(c) == 0) {
				n->children[c] = new node();
			}
			n = n->children[c];
			n->refcnt++;
		}
	}
	void remove(string &word) {
		node *n = &root;
		n->refcnt--;
		word.push_back('#');
		/* we're assuming that word is definitely present;
		 * otherwise we'd first have to look it up. */
		_remove(&root, word, 0);
	}
	int count(string &word) {
		node *n = &root;
		word.push_back('#');
		for (char c : word) {
			if (n->children.count(c) == 0) {
				return 0;
			}
			n = n->children[c];
		}
		return n->refcnt;
	}
	int max_common_prefix_len(string &word) {
		int ret = 0;
		node *n = &root;
		for (char c : word) {
			if (n->children.count(c) == 0) {
				break;
			}
			n = n->children[c];
			ret++;
		}
		return ret;
	}
};

int main()
{
	ifstream in(IA_PROB".in");
	ofstream out(IA_PROB".out");

	Trie trie;

	int op;
	string word;
	while (in>>op>>word) {
		switch (op) {
		case 0:
			trie.insert(word);
			break;
		case 1:
			trie.remove(word);
			break;
		case 2:
			out<<trie.count(word)<<endl;
			break;
		case 3:
			out<<trie.max_common_prefix_len(word)<<endl;
			break;
		default:
			exit(1);
		}
	}

	return 0;
}