Pagini recente » Cod sursa (job #1107895) | Cod sursa (job #2416091) | Istoria paginii runda/bolt/clasament | Cod sursa (job #552133) | Cod sursa (job #2440255)
#include <fstream>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
struct Trie
{
short int cnt_end;
short int cnt;
Trie *kids[26];
Trie()
{
cnt_end = cnt = 0;
for (int i = 0; i < 26; i++)
kids[i] = 0;
}
};
Trie *root = new Trie;
void add(string w)
{
Trie *node = root;
for (auto &ch : w)
{
int x = ch - 'a';
if (node -> kids[x] == 0)
node -> kids[x] = new Trie;
node = node -> kids[x];
node -> cnt++;
}
node -> cnt_end++;
}
void del(string w)
{
Trie *node = root;
for (auto &ch : w)
{
Trie *ant = node;
int x = ch - 'a';
node = node -> kids[x];
node -> cnt--;
if (node -> cnt == 0)
{
ant -> kids[x] = 0;
return;
}
}
node -> cnt_end--;
}
int frq(string w)
{
Trie *node = root;
for (auto &ch : w)
{
int x = ch - 'a';
if (node -> kids[x] == 0)
return 0;
node = node -> kids[x];
}
return node -> cnt_end;
}
int lcp(string w)
{
Trie *node = root;
int sol = 0;
for (auto &ch : w)
{
int x = ch - 'a';
if (node -> kids[x] == 0)
return sol;
sol++;
node = node -> kids[x];
}
return sol;
}
int main()
{
int t;
while (fin >> t)
{
string w;
fin >> w;
if (t == 0)
add(w);
if (t == 1)
del(w);
if (t == 2)
fout << frq(w) << "\n";
if (t == 3)
fout << lcp(w) << "\n";
}
}