Pagini recente » Cod sursa (job #2747696) | Cod sursa (job #265094) | Cod sursa (job #2401463) | Cod sursa (job #382416) | Cod sursa (job #1595115)
#define _CRT_SECURE_NO_WARNINGS
#include <fstream>
#include <vector>
#include <string>
#define TRIE_NUMBER_OF_CHILDREN_PER_NODE 26
using namespace std;
class Node
{
public: // variables
Node* childrens[TRIE_NUMBER_OF_CHILDREN_PER_NODE];
int numberOfChildrens = 0;
int value = 0;
public: // methods
Node()
{
for (int i = 0; i < TRIE_NUMBER_OF_CHILDREN_PER_NODE; i++)
{
this->childrens[i] = NULL;
}
}
~Node()
{
for (int i = 0; i < TRIE_NUMBER_OF_CHILDREN_PER_NODE; i++)
{
if (this->childrens[i] == NULL)
{
continue;
}
delete(this->childrens[i]);
}
}
};
class Trie
{
public: // methods
void AddWord(string word)
{
Node* current = root;
for (string::iterator it = word.begin(); it != word.end(); it++)
{
char c = *it;
int index = c - 'a';
if (current->childrens[index] == NULL)
{
current->numberOfChildrens += 1;
current->childrens[index] = new Node();
}
current = current->childrens[index];
}
current->value += 1;
}
void RemoveWord(string word)
{
Node* current = root;
Node* previous = NULL;
int index = -1;
for (string::iterator it = word.begin(); it != word.end(); it++)
{
char c = *it;
index = c - 'a';
if (current->childrens[index] == NULL)
{
return;
}
previous = current;
current = current->childrens[index];
}
if (current->value > 0)
{
current->value -= 1;
if (current->numberOfChildrens == 0 && previous != NULL)
{
previous->childrens[index] = NULL;
previous->numberOfChildrens -= 1;
delete(current);
}
}
}
int GetNumberOfOccurences(string word)
{
Node* current = root;
for (string::iterator it = word.begin(); it != word.end(); it++)
{
char c = *it;
int index = c - 'a';
if (current->childrens[index] == NULL)
{
return 0;
}
current = current->childrens[index];
}
return current->value;
}
int GetLongestPrefix(string word)
{
Node* current = root;
int longestPrefix = 0;
for (string::iterator it = word.begin(); it != word.end(); it++)
{
char c = *it;
int index = c - 'a';
if (current->childrens[index] == NULL)
{
return longestPrefix;
}
longestPrefix += 1;
current = current->childrens[index];
}
return longestPrefix;
}
~Trie()
{
delete(root);
}
private: // variables
Node* root = new Node();
private: // methods
};
int main()
{
ifstream input("trie.in");
ofstream output("trie.out");
int option;
string word;
Trie trie;
int occurences;
int prefixLength;
while (input >> option >> word)
{
switch (option)
{
case 0:
trie.AddWord(word);
break;
case 1:
trie.RemoveWord(word);
break;
case 2:
occurences = trie.GetNumberOfOccurences(word);
output << occurences << '\n';
break;
case 3:
prefixLength = trie.GetLongestPrefix(word);
output << prefixLength << '\n';
break;
default:
break;
}
}
return 0;
}