Cod sursa(job #749517)

Utilizator BitOneSAlexandru BitOne Data 17 mai 2012 16:09:41
Problema Trie Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;

class Trie {
	int countAp, countSet;
	Trie *nods[30];
	
	bool Del(const char *s) {
		if('\0' == s[0])
		{
			--this->countAp;
			return 0 != this->countAp || 0 != this->countSet;
		}
		int indexC=s[0]-'a';
		
		if(true == nods[indexC]->Del(s+1))
		{
			--countSet;
			delete nods[indexC];
			nods[indexC]=NULL;
		}
		if(0 == countSet && 0 == countAp)
			return true;
		return false;
	}
public:
	Trie() 
	{
		countSet=countAp=0;
		for(int i=0; i < 30; ++i)
			nods[i]=NULL;
	}
	~Trie() 
	{
		for(int i=0; i < 30; ++i)
		{	
			delete nods[i];
			nods[i]=NULL;
		}
	}
	void Add(const char *s) {
		if('\0' == s[0])
		{
			++this->countAp;
			return ;
		}
		int indexC=s[0]-'a';
		if(NULL == nods[indexC])
			nods[indexC]=new Trie(), ++countSet;
		return nods[indexC]->Add(s+1);
	}
	void Delete(const char *s) { Del(s); }
	int CountAp(const char *s) {
		if('\0' == s[0])
			return this->countAp;
		if(NULL == nods[s[0]-'a'])
			return 0;
		return nods[s[0]-'a']->CountAp(s+1);
	}
	int LCP(const char *s) {
		 static int count=0;
		 if('\0' == s[0] || NULL == nods[s[0]-'a'])
			return count;
		 ++count;
		 return nods[s[0]-'a']->LCP(s+1);
	}
} *root=new Trie();

int main()
{
	int op;
	string s;
	ifstream in("trie.in");
	ofstream out("trie.out");
	
	while(in>>op>>s)
	{
		switch(op)
		{
			case 0 : root->Add(s.c_str()); break;
			case 1 : root->Delete(s.c_str()); break;
			case 2 : out<<root->CountAp(s.c_str())<<'\n'; break;
			case 3 : out<<root->LCP(s.c_str())<<'\n'; break;
		}
	}
	
	return EXIT_SUCCESS;
}