Pagini recente » Cod sursa (job #222487) | Cod sursa (job #224742) | Statistici Trial and Error (dannywox969) | Profil Unibuc_Forza_Dragulici | Cod sursa (job #3182081)
#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 0;
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';
}
}