Pagini recente » Cod sursa (job #1056485) | Cod sursa (job #2228611) | Cod sursa (job #2282208) | Cod sursa (job #1492396) | Cod sursa (job #2721875)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
class Trie
{
private:
int cnt = 0;
int lvs = 0;
Trie *next[26] = {};
public:
void insert(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(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(string &str, int pos = 0)
{
if(pos == (int)str.size())
return cnt;
else 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 == (int)str.size())
return 0;
if(!next[str[pos] - 'a'])
return 0;
return 1 + next[str[pos] - 'a'] -> lcp(str, pos + 1);
}
};
int main()
{
Trie trie;
int cod;
string cuv;
while(fin >> cod >> cuv)
{
if(!cod)
{
// adauga o aparitie a cuvantului in trie
trie.insert(cuv);
}
else if(cod == 1)
{
// sterge o aparitie a cuvantului din trie
trie.erase(cuv);
}
else if(cod == 2)
{
// numarul de apartii al cuvantului din trie
fout << trie.count(cuv) << "\n";
}
else
{
// lungimea celui mai lung prefix comun al lui w cu oricare cuvant din trie
fout << trie.lcp(cuv) << "\n";
}
}
return 0;
}