Pagini recente » Borderou de evaluare (job #2234984) | Cod sursa (job #2502422) | Borderou de evaluare (job #2005483) | Borderou de evaluare (job #2089849) | Cod sursa (job #2693393)
#include <fstream>
#include <string>
const int SIGMA = 26;
class Trie
{
private:
int numWords;
int numChildren;
Trie* father;
Trie* children[SIGMA];
public:
Trie(Trie* father = nullptr)
{
this->numWords = 0;
this->numChildren = 0;
this->father = father;
for (int i = 0; i < SIGMA; i++)
this->children[i] = nullptr;
}
void add(std::string word, int pos)
{
if (pos >= word.size())
{
this->numWords++;
return;
}
if (this->children[word[pos] - 'a'] == nullptr)
{
this->children[word[pos] - 'a'] = new Trie(this);
this->numChildren++;
}
this->children[word[pos] - 'a']->add(word, pos + 1);
}
void remove(std::string word, int pos)
{
if (pos >= word.size())
this->numWords--;
else
this->children[word[pos] - 'a']->remove(word, pos + 1);
if (pos > 0 && this->numWords == 0 && this->numChildren == 0)
{
this->father->numChildren--;
this->father->children[word[pos - 1] - 'a'] = nullptr;
delete this;
}
}
int count(std::string word, int pos)
{
if (pos >= word.size())
{
return this->numWords;
}
if (this->children[word[pos] - 'a'] == nullptr)
return 0;
return this->children[word[pos] - 'a']->count(word, pos + 1);
}
int prefix(std::string word, int pos)
{
if(pos >= word.size())
{
return word.size();
}
if (this->children[word[pos] - 'a'] == nullptr)
return pos;
return this->children[word[pos] - 'a']->prefix(word, pos + 1);
}
};
int main()
{
std::ifstream in("trie.in");
std::ofstream out("trie.out");
Trie* trie = new Trie();
int type;
std::string w;
while (in >> type >> w)
{
if (type == 0)
trie->add(w, 0);
else if (type == 1)
trie->remove(w, 0);
else if (type == 2)
out << trie->count(w, 0) << '\n';
else
out << trie->prefix(w, 0) << '\n';
}
return 0;
}