Pagini recente » Cod sursa (job #2225480) | Cod sursa (job #2736666) | Cod sursa (job #1343446) | Cod sursa (job #2077020) | Cod sursa (job #2919793)
#include <bits/stdc++.h>
#pragma GCC optimize ("Ofast")
using namespace std;
ifstream fin ("trie.in");
ofstream fout ("trie.out");
int type;
string word;
struct trie{
int lcnt, terminal;
trie *leaf[26];
trie(){
lcnt = terminal = 0;
for(int i=0; i < 26; i++)
leaf[i] = NULL;
}
} *tr = new trie;
inline void update(trie *nod, int index, int limit, int modif){
int letter = word[index] - 'a';
nod->lcnt += modif;
if(index < limit){
if(nod->leaf[letter] == NULL)
nod->leaf[letter] = new trie;
update(nod->leaf[letter], index+1, limit, modif);
}else
nod->terminal += modif;
}
inline int get_freq(trie *nod, int index, int limit){
int letter = word[index] - 'a';
if(index < limit){
if(nod->leaf[letter] == NULL || nod->leaf[letter]->lcnt == 0)
return 0;
return get_freq(nod->leaf[letter], index+1, limit);
}else
return nod->terminal;
}
inline int prefix(trie *nod, int index, int limit){
int letter = word[index] - 'a';
if(index < limit){
if(nod->leaf[letter] == NULL || nod->leaf[letter]->lcnt == 0)
return index;
return prefix(nod->leaf[letter], index+1, limit);
}else
return index;
}
int main (){
ios_base::sync_with_stdio(false);
fin.tie(nullptr), fout.tie(nullptr);
while(fin>>type){
fin>>word;
if(type == 0) /// add word
update(tr, 0, (int)word.size(), +1);
if(type == 1) /// rem word
update(tr, 0, (int)word.size(), -1);
if(type == 2) /// query freq
fout<<get_freq(tr, 0, (int)word.size())<<"\n";
if(type == 3) /// query prefix
fout<<prefix(tr, 0, (int)word.size())<<"\n";
}
return 0;
}