Pagini recente » Cod sursa (job #1714862) | Cod sursa (job #608425) | Cod sursa (job #56444) | Cod sursa (job #1990205) | Cod sursa (job #2965043)
#include <bits/stdc++.h>
using namespace std;
ifstream in("trie.in");
ofstream out("trie.out");
class Trie
{
int cnt = 0;
int lvs = 0;
Trie *next[26] = {};
public:
void insert(const string& s, int poz = 0)
{
lvs++;
if(poz == s.size())
cnt++;
else
{
if(!next[s[poz] - 'a'])
next[s[poz] - 'a'] = new Trie;
next[s[poz] - 'a']->insert(s, poz + 1);
}
}
void erase(const string& s, int poz = 0)
{
lvs--;
if(poz == s.size())
cnt--;
else
{
next[s[poz] - 'a']->erase(s, poz + 1);
if(!next[s[poz] - 'a']->lvs)
{
delete next[s[poz] - 'a'];
next[s[poz] - 'a'] = nullptr;
}
}
}
int count(const string& s, int poz = 0)
{
if(poz == s.size())
return cnt;
if(!next[s[poz] - 'a'])
return 0;
return next[s[poz] - 'a']->count(s, poz + 1);
}
int lcp(const string& s, int poz = 0)
{
if(poz == s.size())
return 0;
if(!next[s[poz] - 'a'])
return 0;
return 1 + next[s[poz] - 'a']->lcp(s, poz + 1);
}
};
int main()
{
Trie trie;
int op;
string s;
while(in >> op >> s)
{
if(op == 0)
trie.insert(s);
else if(op == 1)
trie.erase(s);
else if(op == 2)
out << trie.count(s) << '\n';
else
out << trie.lcp(s) << '\n';
}
return 0;
}