Cod sursa(job #944409)

Utilizator howsiweiHow Si Wei howsiwei Data 28 aprilie 2013 14:02:19
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.55 kb
#include <fstream>
#include <map>
using namespace std;

class Trie {
public:
	Trie() {
		root = new Node();
	}

	void insert( char * s ) {
		Node * t = root;
		for (int i = 0; ; ++i) {
			if (t->child[s[i]] == NULL) {
				t->child[s[i]] = new Node;
			}
			t = t->child[s[i]];
			++t->cnt_pre;
			if (s[i] == '\0') return;
		}
	}

	void remove( char * s ) { // s must be in trie 
		remove(s, root);
	}

	int count( char * s, bool whole = true ) {
		Node * t = root;
		for (int i = 0; ; ++i) {
			if (s[i] == '\0' && whole == false) break;
			if (t->child[s[i]] == NULL) return 0;
			t = t->child[s[i]];
			if (s[i] == '\0') break;
		}
		return t->cnt_pre;
	}

	int lenMatchPre( char * s ) {
		Node * t = root;
		for (int i = 0; ; ++i) {
			if (s[i] == '\0') return i;
			if (t->child[s[i]] == NULL) return i;
			t = t->child[s[i]];
		}
	}

private:
	struct Node {
		Node() : cnt_pre(0) { }
		map<char, Node *> child;
		int cnt_pre;
	};

	Node * root;

	void remove( char * s, Node * & p ) {
		Node * t = p->child[s[0]];
		if (s[0] != '\0') {
			remove(s+1, t);
		}
		--t->cnt_pre;
		if (t->cnt_pre == 0) {
			delete t;
			p->child.erase(s[0]);
		}
	}
};

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

	Trie dict;
	short op;
	char s[30];
	
	while (fin >> op) {
		fin >> s;
		switch (op) {
			case 0: dict.insert(s); break;
			case 1: dict.remove(s); break;
			case 2: fout << dict.count(s) << '\n'; break;
			case 3: fout << dict.lenMatchPre(s) << '\n'; break;
		}
	}

	return 0;
}