Pagini recente » Cod sursa (job #1555804) | Cod sursa (job #1102747) | Cod sursa (job #3166099) | Cod sursa (job #1891320) | Cod sursa (job #3220913)
#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]={};
};
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';
if (tri->occ[alp]==1) {
delete tri->alfa[alp];
tri->alfa[alp] = nullptr;
tri->occ[alp]--;
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++;
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]++;
//cout<<1<<' '<<word<<' '<<mp[word]<<' '<<root->alfa[word[0]-'a']<<endl;
}
if (n==1) {
mp[word]--;
if (mp[word]<=0) remove_from_trie(word, 0, root);
//cout<<1<<' '<<word<<' '<<mp[word]<<' '<<root->alfa[word[0]-'a']<<endl;
}
if (n==2) {
fout<<mp[word]<<'\n';
}
if (n==3) {
int maxi_siz=0;
//cout<<word<<' ';
longest_prefix(word, maxi_siz, root);
//cout<<endl;
fout<<maxi_siz<<'\n';
}
}
delete root;
return 0;
}