Cod sursa(job #1259471)

Utilizator ucc_5Usurelu Catalin ucc_5 Data 10 noiembrie 2014 00:44:27
Problema Trie Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
#include <fstream>
#include <cstring>
#include <iostream>

#define NUM_CHARS 255

using namespace std;


class Node
{
private:
	Node* son[NUM_CHARS];
	int cnt;
	int countSons;

public:
	Node()
	{
		memset(son, 0, NUM_CHARS * sizeof(Node*));
		cnt = 0;
		countSons = 0;
	}

	void insert(char* cuv)
	{
		if(*cuv == 0)
		{
			cnt++;
			return;
		}

		if(son[*cuv] == 0)
		{
			son[*cuv] = new Node();
			countSons++;
		}

		son[*cuv]->insert(cuv + 1);
	}

	void erase(char* cuv)
	{
		if(*cuv == 0)
		{
			cnt--;
			return;
		}

		son[*cuv]->erase(cuv + 1);

		if(son[*cuv]->countSons == 0 && son[*cuv]->cnt == 0)
		{
			delete son[*cuv];
			son[*cuv] = NULL;
			countSons--;
			return;
		}
	}

	int count(char* cuv)
	{
		if(*cuv == 0)
		{
			return cnt;
		}

		if(son[*cuv] == 0)
		{
			return 0;
		}

		return son[*cuv]->count(cuv + 1);
	}

	int commonPrefixLength(char* cuv, int len)
	{
		if(*cuv == 0 || son[*cuv] == 0)
		{
			return len;
		}

		return son[*cuv]->commonPrefixLength(cuv + 1, len + 1);
	}

};

int main()
{
	ifstream f("trie.in");
	ofstream g("trie.out");

	char cuv[20];
	int op = 0;
	Node* root = new Node();

	while(f >> op >> cuv)
	{
		switch(op)
		{
			
			case 0:	root->insert(cuv); break;
			case 1: root->erase(cuv); break;
			case 2: g << root->count(cuv) << endl; break;
			case 3: g << root->commonPrefixLength(cuv, 0) << endl;; break;
		}
	}
}