Pagini recente » Cod sursa (job #1867001) | Cod sursa (job #1175873) | Cod sursa (job #878932) | Cod sursa (job #312279) | Cod sursa (job #2976231)
#include <iostream>
using namespace std;
struct Trie
{
int e = 0,trec = 0;
Trie *next[26] = {nullptr};
void baga(string &s,int p = 0)
{
trec++;
if(p == s.size())
{
e++;
return;
}
if(!next[s[p] - 'a'])
{
Trie *nou = new Trie;
next[s[p] - 'a'] = nou;
}
next[s[p] - 'a']->baga(s,p + 1);
}
int check(string &s,int p = 0)
{
if(p == s.size())
return e;
if(!next[s[p] - 'a'])
return 0;
return next[s[p] - 'a']->check(s,p + 1);
}
void sterge(string &s,int p = 0)
{
trec--;
if(p == s.size())
{
e--;
return;
}
if(!next[s[p] - 'a'])
return;
next[s[p] - 'a']->sterge(s,p + 1);
if(!next[s[p] - 'a']->trec)
{
delete next[s[p] - 'a'];
next[s[p] - 'a'] = nullptr;
}
}
int lcp(string &s,int p = 0)
{
if(p == s.size()) return p;
if(!next[s[p] - 'a']) return p;
return next[s[p] - 'a']->lcp(s,p + 1);
}
};
int main()
{
freopen("trie.in" , "r" , stdin);
freopen("trie.out" , "w" ,stdout);
cin.tie(0)->sync_with_stdio(0);
Trie *trie = new Trie;
string s; int op;
while(cin >> op >> s)
{
switch(op)
{
case 1: trie->sterge(s); break;
case 2: cout << trie->check(s) << '\n'; break;
case 3: cout << trie->lcp(s) << '\n'; break;
case 0: trie->baga(s); break;
}
}
}