Cod sursa(job #831322)

Utilizator axnsanCristi Vijdea axnsan Data 8 decembrie 2012 14:22:09
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.96 kb
#include <iostream>
#include <fstream>
using namespace std;
const unsigned MAX_LEN = 20U;
const unsigned SIGMA = 26U;
class Trie
{
public:
	Trie() : Root(new Node) {}
	void Add(const char* w);
	void Delete(const char* w);
	unsigned Count(const char* w);
	unsigned LongestPrefixOf(const char* w);

private:
	struct Node {
		Node *Children[SIGMA];
		unsigned Count;
		unsigned char numChildren;
		Node() : Count(0), numChildren(0) { memset(Children, 0, sizeof Children); }
		inline void AddChild(char c) { if (Children[c] == NULL) { Children[c] = new Node; ++numChildren; } }
		inline void RemoveChild(char c) { if (Children[c] != NULL) { delete Children[c]; Children[c] = NULL; --numChildren; } }
		/*~Node() { 
			for (unsigned i = 0;i < SIGMA;++i)
				delete Children[i];
		}*/
	} *const Root;
};
int main()
{
	ifstream f("trie.in");
	ofstream g("trie.out");
	unsigned opCode;
	char w[21];
	Trie T;
	while (f >> opCode >> w)
	{
		switch (opCode)
		{
		case 0:
			T.Add(w);
			break;
		case 1:
			T.Delete(w);
			break;
		case 2:
			g << T.Count(w) << '\n';
			break;
		case 3:
			g << T.LongestPrefixOf(w) << '\n';
			break;
		}
	}
	f.close();
	g.flush();
	g.close();

	return 0;
}

void Trie::Add(const char* w)
{
	Node* n = Root;
	while (*w)
	{
		n->AddChild(*w-'a');
		n = n->Children[*w-'a'];
		++w;
	}
	++(n->Count);
}
unsigned Trie::Count(const char* w)
{
	Node* n = Root;
	while (*w && n != NULL)
		n = n->Children[*w++ -'a'];

	if (n != NULL)
		return n->Count;
	
	return 0;
}
void Trie::Delete(const char* w)
{
	Node* n[MAX_LEN];
	unsigned i = 0;
	n[0] = Root;
	while (*w)
		n[i+1] = n[i++]->Children[*w++ -'a'];

	--(n[i]->Count);
	while (n[i]->Count == 0 && n[i]->numChildren == 0 && i > 0)
		n[--i]->RemoveChild(*(--w)-'a');
}
unsigned Trie::LongestPrefixOf(const char* w)
{
	Node* n = Root;
	const char *p = w;
	while (*p && n != NULL)
		n = n->Children[*p++ -'a'];

	return p - w - 1;
}