Cod sursa(job #2038561)

Utilizator robuvedVictor Robu robuved Data 13 octombrie 2017 19:54:37
Problema Trie Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.74 kb
#include <fstream>
#include <string>
using namespace std;

ifstream in("trie.in");
ofstream out("trie.out");
#define MAX ('z' - 'a' + 1)
struct Node 
{
	Node* children[MAX];
	int count[MAX];
	Node()
	{
		for (int i = 0; i < MAX; i++)
		{
			count[i] = 0;
			children[i] = nullptr;
		}
	}
};
Node root;
void InsertWord(string word)
{
	Node *p = &root;
	for (auto it = word.begin(); it != word.end() - 1; it++)
	{
		int index = *it - 'a';
		if (p->children[index] == nullptr)
			p->children[index] = new Node();
		p = p->children[index];
	}
	int index = word.back() - 'a';
	p->count[index]++;
}
void DeleteWord(string word)
{
	Node *p = &root;
	for (auto it = word.begin(); it != word.end() - 1; it++)
	{
		int index = *it - 'a';
		if (p->children[index] == nullptr)
			return;
		p = p->children[index];
	}
	int index = word.back() - 'a';
	p->count[index]--;
}
int CountWord(string word)
{
	Node *p = &root;
	for (auto it = word.begin(); it != word.end() - 1; it++)
	{
		int index = *it - 'a';
		if (p->children[index] == nullptr)
			return 0;
		p = p->children[index];
	}
	int index = word.back() - 'a';
	return p->count[index];
}
int LongestPrefix(string word)
{
	Node *p = &root;
	auto it = word.begin();
	for (; it != word.end() && p->children[*it - 'a']; it++)
	{
		p = p->children[*it - 'a'];
	}
	int longest = it - word.begin();
	if (p->count[*it - 'a'] > 0)
		longest++;
	return longest;
}
int main()
{
	int opt;
	string word;
	while (in >> opt >> word)
	{
		switch (opt)
		{
		case 0:
			InsertWord(word);
			break;
		case 1:
			DeleteWord(word);
			break;
		case 2:
			out << CountWord(word) << '\n';
			break;
		case 3:
			out << LongestPrefix(word) << '\n';
			break;
		}
	}
}