Pagini recente » Cod sursa (job #328003) | Cod sursa (job #2973912)
#include <fstream>
using namespace std;
ifstream cin("trie.in");
ofstream cout("trie.out");
int op ;
string a;
struct trie{
int cnt = 0 , frunze = 0;
trie * next[26] = {nullptr};
void ins( string &a , int pos = 0){
frunze++;
if(pos == a.size()){
cnt++;
return;
}
if(!next[a[pos] - 'a']){
next[a[pos] - 'a'] = new trie;
}
next[a[pos]-'a'] ->ins(a , pos+1);
}
void stergere( string &a , int pos = 0){
frunze--;
if(pos == a.size()){
cnt--;
}else{
next[a[pos]-'a'] -> stergere(a,pos+1);
if(!next[a[pos]-'a'] -> frunze){
delete next[a[pos]-'a'];
next[a[pos]-'a'] = nullptr;
}
}
}
int aparitii(string &a , int pos = 0){
if(pos == a.size()){
return cnt;
}
if(!next[a[pos] - 'a']){
return 0;
}
return next[a[pos] - 'a'] -> aparitii(a,pos+1);
}
int prefix( string &a , int pos = 0){
if(pos == a.size()){
return 0;
}
if(!next[a[pos]-'a']){
return 0;
}
return 1 + next[a[pos]-'a'] -> prefix(a,pos+1);
}
}t;
int main(){
while( cin >> op >> a){
if(op == 0) t.ins(a);
if(op == 1) t.stergere(a);
if(op == 2) cout << t.aparitii(a) << '\n';
if(op == 3) cout << t.prefix(a) << '\n';
}
return 0;
}