Pagini recente » Cod sursa (job #1687080) | Cod sursa (job #370224) | Cod sursa (job #1862304) | Cod sursa (job #1055219) | Cod sursa (job #3220920)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
unordered_map <string, int> mp;
struct trie
{
trie *alfa[26]={};
int occ[26]={};
};
//int cnt=0, in=0;
void add_to_trie (string word, int index, trie *tri) {
if (index==word.size()) return;
char c=word[index];
int alp=c-'a';
tri->occ[alp]++;
if (tri->alfa[alp]==nullptr) {
trie *ne=new trie;
tri->alfa[alp]=ne;
}
add_to_trie(word, index+1, tri->alfa[alp]);
}
void remove_from_trie(string word, int index, trie *tri)
{
if (index==word.size()) return;
char c=word[index];
int alp=c-'a';
tri->occ[alp]--;
if (tri->occ[alp]==0) {
delete tri->alfa[alp];
tri->alfa[alp] = nullptr;
return;
}
remove_from_trie(word, index+1, tri->alfa[alp]);
}
void longest_prefix (string word, int &index, trie *tri)
{
if (index==word.size()) return;
char c=word[index];
int alp=c-'a';
if (tri->alfa[alp]!=nullptr) {
index++;
//if (cnt==13786) cout<<c<<' '<<tri->occ[alp]<<endl;
longest_prefix(word, index, tri->alfa[alp]);
}
}
int main()
{
fin.tie(0); fin.sync_with_stdio(false);
int n; string word;
trie *root=new trie;
while (fin>>n>>word) {
if (n==0) {
if (mp[word]==0) add_to_trie(word, 0, root);
mp[word]++;
}
if (n==1) {
if (mp[word]>0) mp[word]--;
if (mp[word]==0) remove_from_trie(word, 0, root);
}
if (n==2) {
fout<<mp[word]<<'\n';
}
if (n==3) {
int maxi_siz=0;
longest_prefix(word, maxi_siz, root);
fout<<maxi_siz<<'\n';
}
}
delete root;
return 0;
}