Cod sursa(job #1448427)

Utilizator mouse_wirelessMouse Wireless mouse_wireless Data 7 iunie 2015 01:50:17
Problema Trie Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.49 kb
#include <cstdio>
#include <cassert>
#include <cstring>
#include <algorithm>
#include <list>
using namespace std;
#define _submit
#ifdef _submit
#define InFile "trie.in"
#define OtFile "trie.out"
#else
#define InFile "fis.in"
#define OtFile "fis.out"
#endif

class trie {
private:
	int c;
	list<trie*> next;
public:
	trie() {
		c = 0;
		next.clear();
	}
	trie(int ch) {
		c = ch;
		next.clear();
	}
	void insert(char* word) {
		int ch = (int)*word;
		if (ch == 0) {
			for (auto i = next.begin(); i != next.end(); ++i)
			if ((*i)->c & 0x8000) {
				(*i)->c++;
				return;
			}
			trie* T = new trie(0x8001);
			next.push_back(T);
		}
		else {
			for (auto i = next.begin(); i != next.end(); ++i)
			if ((*i)->c == ch) {
				(*i)->insert(word + 1);
				return;
			}
			trie* T = new trie(ch);
			next.push_back(T);
			T->insert(word + 1);
		}
	}
	bool remove(char* word) {
		int ch = (int)*word;
		if (ch == 0) {
			for (auto i = next.begin(); i != next.end(); ++i)
			if ((*i)->c & 0x8000) {
				(*i)->c--;
				if ((((*i)->c) & 0x7FFF) == 0) {
					next.erase(i);
					if (next.size() == 0)
						return true;
				}
				return false;
			}
			return false;
		}
		else {
			for (auto i = next.begin(); i != next.end(); ++i)
			if ((*i)->c == ch) {
				bool tmp = (*i)->remove(word + 1);
				if (tmp) {
					next.erase(i);
					if (next.size() == 0)
						return true;
				}
				return false;
			}
			return false;
		}
		return false;
	}
	int nrap(char* word) {
		int ch = (int)*word;
		if (ch == 0) {
			for (auto i = next.begin(); i != next.end(); ++i)
			if ((*i)->c & 0x8000) {
				return (((*i)->c) & 0x7FFF);
			}
		}
		else {
			for (auto i = next.begin(); i != next.end(); ++i)
			if ((*i)->c == ch) {
				return (*i)->nrap(word + 1);
			}
		}
		return 0;
	}
	int longestPrefxLength(char* word) {
		int ch = (int)*word;
		if (ch == 0)
			return 0;
		else {
			for (auto i = next.begin(); i != next.end(); ++i)
			if ((*i)->c == ch) {
				return 1 + (*i)->longestPrefxLength(word + 1);
			}
		}
		return 0;
	}
};

int main() {
	assert(freopen(InFile, "r", stdin));
	assert(freopen(OtFile, "w", stdout));
	int op;
	char w[25];
	trie* T = new trie;
	while (scanf("%d%s", &op, w) != EOF) {
		switch (op)
		{
		case 0:
			T->insert(w);
			break;
		case 1:
			T->remove(w);
			break;
		case 2:
			printf("%d\n", T->nrap(w));
			break;
		default:
			printf("%d\n", T->longestPrefxLength(w));
			break;
		}
	}
	return 0;
}