Pagini recente » Cod sursa (job #1525421) | Istoria paginii summer-challenge-2009/solutii/runda-2 | Cod sursa (job #3225235) | Cod sursa (job #2550468) | Cod sursa (job #1514214)
#include <bits/stdc++.h>
using namespace std;
class Trie {
private:
int freq, below;
Trie* sons[26];
public:
Trie()
{
freq = below = 0;
memset(sons, 0, sizeof(sons));
}
void add(const string &S, int value)
{
Trie *T = this;
for (auto it : S)
{
auto edge = it - 'a';
if (T->sons[edge] == 0)
T->sons[edge] = new Trie;
T = T->sons[edge], T->below += value;
}
T->freq += value;
}
int lcp(const string &S)
{
Trie *T = this;
int res = 0;
for (auto it : S)
{
auto edge = it - 'a';
if (T->sons[edge] == 0 or T->sons[edge]->below == 0)
return res;
T = T->sons[edge];
res++;
}
return static_cast<int>(S.size());
}
int ff(const string &S)
{
Trie *T = this;
for (auto it : S)
{
auto edge = it - 'a';
if (T->sons[edge] == 0)
return 0;
T = T->sons[edge];
}
return T->freq;
}
};
int main() {
ifstream cin("trie.in");
ofstream cout("trie.out");
int todo;
string S;
Trie *T = new Trie;
while (cin >> todo >> S) {
if (todo == 0)
T->add(S, 1);
else
if (todo == 1)
T->add(S, -1);
else
if (todo == 2)
cout << T->ff(S) << '\n';
else
cout << T->lcp(S) << '\n';
}
return 0;
}