Pagini recente » Cod sursa (job #2904519) | Cod sursa (job #1147699) | Cod sursa (job #642126) | Cod sursa (job #1522389) | Cod sursa (job #1986560)
#include <iostream>
#include <fstream>
#include <cassert>
using namespace std;
inline int toInt(char x)
{
return x - 'a';
}
class Trie
{
public:
Trie()
{
cnt = 0;
nrChildren = 0;
for(int i = 0; i < 26; ++i)
child[i] = nullptr;
}
void Insert(char *s)
{
if(s[0] == '\0')
{
++cnt;
return;
}
int c = toInt(s[0]);
if(child[c] == nullptr)
{
nrChildren++;
child[c] = new Trie();
}
child[c]->Insert(s + 1);
}
bool Delete(char *s)
{
if(s[0] == '\0')
{
--cnt;
if(cnt == 0 && nrChildren == 0)
return true;
return false;
}
int c = toInt(s[0]);
assert(child[c] != nullptr);
if(child[c]->Delete(s + 1))
{
delete child[c];
child[c] = nullptr;
nrChildren--;
if(cnt == 0 && nrChildren == 0)
return true;
}
return false;
}
int Find(char *s)
{
if(s[0] == '\0')
return cnt;
int c = toInt(s[0]);
if(child[c] == nullptr)
return 0;
return child[c]->Find(s + 1);
}
int Pref(char *s, int mx = 0)
{
char c = toInt(s[0]);
if(s[0] == '\0' || child[c] == nullptr)
return mx;
return child[c]->Pref(s + 1, mx + 1);
}
private:
int cnt;
int nrChildren;
Trie * child[26];
};
int main()
{
ifstream in("trie.in");
ofstream out("trie.out");
Trie t;
int x;
char cuv[25];
while(in >> x && in >> cuv)
{
if(x == 0)
t.Insert(cuv);
else if(x == 1)
t.Delete(cuv);
else if(x == 2)
out << t.Find(cuv) << "\n";
else if(x == 3)
out << t.Pref(cuv) << "\n";
}
return 0;
}