Pagini recente » Istoria paginii utilizator/upsolve | Diferente pentru utilizator/marius0072 intre reviziile 36 si 37 | Istoria paginii utilizator/claudiu.ncl | Diferente pentru planificare/sedinta-20110801 intre reviziile 4 si 3 | Cod sursa (job #3182079)
#include <bits/stdc++.h>
using namespace std;
class Trie
{
int cnt = 0;
int lvs = 0;
Trie *next[26] = {};
public:
void Insert (string str , int pos = 0)
{
++lvs;
if(str.size() == pos)
++cnt;
else
{
if(!next[str[pos] - 'a'])
next[str[pos] - 'a'] = new Trie;
next[str[pos] - 'a']->Insert(str , pos + 1);
}
}
void Erase (string str , int pos = 0)
{
--lvs;
if(str.size() == pos)
--cnt;
else
{
next[str[pos] - 'a']->Erase(str , pos + 1);
if(!next[str[pos] - 'a']->lvs)
{
delete next[str[pos] - 'a'];
next[str[pos] - 'a'] = nullptr;
}
}
}
int Count (string str , int pos = 0)
{
if(pos == str.size())
return cnt;
if(!next[str[pos] - 'a'])
return 0;
return next[str[pos] - 'a']->Count(str , pos + 1);
}
int LCP (string str, int pos = 0)
{
if(pos == str.size())
return cnt;
if(!next[str[pos] - 'a'])
return 0;
return 1 + next[str[pos] - 'a']->LCP(str , pos + 1);
}
}trie;
int main()
{
int op;
string str;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
while(fin >> op >> str)
{
if(op == 0)
trie.Insert(str);
else if(op == 1)
trie.Erase(str);
else if(op == 2)
fout << trie.Count(str) << '\n';
else
fout << trie.LCP(str) << '\n';
}
}