Cod sursa(job #1231817)

Utilizator andreioneaAndrei Onea andreionea Data 21 septembrie 2014 16:52:59
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <fstream>
#include <string>
#include <algorithm>

struct TrieNode
{
	int appearances;
	int substr;
	TrieNode* cont[26];
	TrieNode();
	static TrieNode* CreateRootNode();
	void AddWord(const char*);
	void RemWord(const char*);
	int ComputeAppearances(const char*);
	int ComputeMaxSubstr(const char*);

};


TrieNode::TrieNode() : appearances(0), substr(0)
{
	for (int i = 0; i < 26; ++i)
		cont[i] = NULL;
}

TrieNode* TrieNode::CreateRootNode()
{
	TrieNode* tn = new TrieNode();
	tn->substr = -300000;
	for (int i = 0; i < 26; ++i)
		tn->cont[i] = new TrieNode();
	return tn;
}

void TrieNode::AddWord(const char* word)
{
	if (!*word) {
		++appearances;
		++substr;
	}
	else {
		++substr;
		char c = *word - 'a';
		if (!cont[c])
			cont[c] = new TrieNode();
		cont[c]->AddWord(word + 1);
	}
}

void TrieNode::RemWord(const char* word)
{
	if (!*word){
		--appearances;
		--substr;
	}
	else {
		--substr;
		char c = *word - 'a';
		cont[c]->RemWord(word + 1);
	}
}

int TrieNode::ComputeMaxSubstr(const char* word)
{
	if (!this || !*word) {
		return 0;
	}

	int add = 0;
	if (substr > 0)
		++add;
	return add + cont[*word - 'a']->ComputeMaxSubstr(word + 1);
}

int TrieNode::ComputeAppearances(const char* word)
{
	if (!this)
		return 0;
	if (!*word)
		return appearances;
	return cont[*word - 'a']->ComputeAppearances(word + 1);
}

int main()
{
	char line[30];
	std::ifstream fin("trie.in");
	std::ofstream fout("trie.out");
	TrieNode* tn = TrieNode::CreateRootNode();
	while (fin.getline(line, 30)) {
		int ret;
		switch (*line) {
			case '0':
				tn->AddWord(line+2);
				break;
			case '1':
				tn->RemWord(line+2);
				break;
			case '2':
				ret = tn->ComputeAppearances(line + 2);
				fout << ret << "\n";
				break;
			case '3':
				fout << tn->ComputeMaxSubstr(line + 2) << "\n";
				break;	
		}
	}
	fin.close();
	fout.close();
	return 0;
}