Pagini recente » Cod sursa (job #1297575) | Istoria paginii runda/oni2013_cls10/clasament | Cod sursa (job #2821098) | Cod sursa (job #472553) | Cod sursa (job #2553561)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
ifstream fin("trie.in");
ofstream fout("trie.out");
int cn(char c){
return (c-'a');
}
struct trie{
trie *son[26];
int v = 0, k = 0;
void iadd(const string &s, int ind=0){
int a = cn(s[ind]);
if(!son[a]){
k++;
son[a] = new trie();
}
if(ind == s.size()-1){
son[a]->v++;
}else{
son[a]->iadd(s, ind+1);
}
}
void iraze(const string &s, int ind=0){
int a = cn(s[ind]);
if(ind == s.size()-1){
son[a]->v--;
}else{
son[a]->iraze(s, ind+1);
}
if(son[a]->v == 0 && son[a]->k == 0){
delete son[a];
son[a] = NULL;
k--;
}
}
int ifind(const string &s, int ind=0){
int a = cn(s[ind]);
if(son[a]){
if(ind == s.size()-1){
return son[a]->v;
}else{
return son[a]->ifind(s, ind+1);
}
}else{
return 0;
}
}
int iprefix(const string &s, int ind=0){
int a = cn(s[ind]);
if(son[a] && ind<s.size()){
return son[a]->iprefix(s, ind+1);
}else{
return ind;
}
}
};
trie *root = new trie();
int main(){
//ios_base::sync_with_stdio(false);
int op;
string s;
while(fin >> op >> s){
if(op == 0){
root->iadd(s);
}else if(op == 1){
root->iraze(s);
}else if(op == 2){
fout << root->ifind(s) << "\n";
}else{
fout << root->iprefix(s) << "\n";
}
}
return 0;
}