Pagini recente » Cod sursa (job #2303565) | Cod sursa (job #1661804) | Cod sursa (job #1348100) | Cod sursa (job #3189369) | Cod sursa (job #3274711)
#include <fstream>
#define FAST ios_base::sync_with_stdio(false);
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
class Trie
{
int cnt=0;
int lvs=0;
Trie *next[26]={};
public:
void insert(const string& str, int pos = 0) {
lvs++;
if (pos == int(str.size()))
cnt++;
else {
if (!next[str[pos] - 'a'])
next[str[pos] - 'a'] = new Trie;
next[str[pos] - 'a']->insert(str, pos + 1);
}
}
void erase(const string& str, int pos = 0) {
lvs--;
if (pos == int(str.size()))
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(const string& str, int pos = 0) {
if (pos == int(str.size()))
return cnt;
if (!next[str[pos] - 'a'])
return 0;
return next[str[pos] - 'a']->count(str, pos + 1);
}
int lcp(const string& str, int pos = 0) {
if (pos == int(str.size()))
return 0;
if (!next[str[pos] - 'a'])
return 0;
return 1 + next[str[pos] - 'a']->lcp(str, pos + 1);
}
};
int main()
{
FAST
Trie trie;
int tip; string s;
while(cin>>tip>>s)
{
switch(tip)
{
case 0: trie.insert(s); break;
case 1: trie.erase(s); break;
case 2: cout<<trie.count(s)<<'\n'; break;
case 3: cout<<trie.lcp(s)<<'\n'; break;
}
}
return 0;
}