Pagini recente » Cod sursa (job #1692628) | Cod sursa (job #2373731) | Cod sursa (job #2876869) | Cod sursa (job #2762550) | Cod sursa (job #3039476)
#include <fstream>
#include <string>
using namespace std;
string s;
class Trie
{
private:
static const int SIGMA = 26;
int frecventa;
Trie* tata;
Trie* fii[Trie::SIGMA];
int pozInTata;
public:
Trie() : frecventa(0), tata(nullptr), pozInTata(-1)
{
for (int i = 0; i < Trie::SIGMA; i++)
this->fii[i] = nullptr;
}
void adauga(string& s, int index = 0)
{
if (index >= s.size())
{
this->frecventa++;
return;
}
if (this->fii[s[index] - 'a'] == nullptr)
{
this->fii[s[index] - 'a'] = new Trie();
this->fii[s[index] - 'a']->tata = this;
this->fii[s[index] - 'a']->pozInTata = s[index] - 'a';
}
this->fii[s[index] - 'a']->adauga(s, index + 1);
}
void elimina(string& s, int index = 0)
{
if (index >= s.size())
this->frecventa--;
else
this->fii[s[index] - 'a']->elimina(s, index + 1);
int nrFiiActivi = 0;
for (int i = 0; i < Trie::SIGMA; i++)
if (this->fii[i] != nullptr)
nrFiiActivi++;
if (nrFiiActivi == 0 && this->frecventa == 0 && this->tata != nullptr)
{
this->tata->fii[this->pozInTata] = nullptr;
delete this;
}
}
int numarare(string& s, int index = 0)
{
if (index >= s.size())
return this->frecventa;
if (this->fii[s[index] - 'a'] != nullptr)
return this->fii[s[index] - 'a']->numarare(s, index + 1);
else
return 0;
}
int sol(string& s, int index = 0)
{
if (index >= s.size())
return 0;
if (this->fii[s[index] - 'a'] != nullptr)
return 1 + this->fii[s[index] - 'a']->sol(s, index + 1);
else
return 0;
}
~Trie()
{
for (int i = 0; i < Trie::SIGMA; i++)
if (this->fii[i] != nullptr)
delete this->fii[i];
}
};
int main()
{
ifstream in("trie.in");
ofstream out("trie.out");
ios_base::sync_with_stdio(false);
in.tie(nullptr);
int tip;
Trie* trie = new Trie();
while (in >> tip >> s)
{
if (tip == 0)
trie->adauga(s);
else if (tip == 1)
{
trie->elimina(s);
}
else if (tip == 2)
{
out << trie->numarare(s) << '\n';
}
else
{
out << trie->sol(s) << '\n';
}
}
delete trie;
in.close();
out.close();
return 0;
}