Pagini recente » Cod sursa (job #2235481) | Cod sursa (job #3277002) | Cod sursa (job #2235479) | Cod sursa (job #3280748) | Cod sursa (job #3276906)
#include <bits/stdc++.h>
using namespace std;
#define INFILE "trie.in"
#define OUTFILE "trie.out"
const int CHILDREN_MAX = 26;
class Trie {
private:
int cnt = 0;
int level = 0;
Trie *children[CHILDREN_MAX] = {};
public:
void insertWord(string s, int position = 0){
++level;
if(s.size() == position) ++cnt;
else {
int to = s[position] - 'a';
if(!children[to]) children[to] = new Trie;
children[to] -> insertWord(s, position + 1);
}
}
void removeWord(string s, int position = 0){
--level;
if(s.size() == position) --cnt;
else {
int to = s[position] - 'a';
children[to] -> removeWord(s, position + 1);
if(!children[to] -> level){
delete children[to];
children[to] = NULL;
}
}
}
int countWord(string s, int position = 0){
++level;
if(s.size() == position) return cnt;
int to = s[position] - 'a';
if(!children[to]) return 0;
return children[to] -> countWord(s, position + 1);
}
int longestCommonPrefix(string s, int position = 0){
if(s.size() == position) return 0;
int to = s[position] - 'a';
if(!children[to]) return 0;
return 1 + children[to] -> longestCommonPrefix(s, position + 1);
}
};
void solve(){
Trie *root = new Trie;
int type; string s;
while(cin >> type >> s){
if(type == 0) root -> insertWord(s);
else if(type == 1) root -> removeWord(s);
else if(type == 2) cout << root -> countWord(s) << '\n';
else cout << root -> longestCommonPrefix(s) << '\n';
}
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
freopen(INFILE, "r", stdin);
freopen(OUTFILE, "w", stdout);
solve();
return 0;
}