Pagini recente » Cod sursa (job #2852739) | Cod sursa (job #2734700) | Cod sursa (job #3229651) | Cod sursa (job #644055) | Cod sursa (job #3263628)
#include <bits/stdc++.h>
using namespace std;
#define INFILE "trie.in"
#define OUTFILE "trie.out"
const int DICTIONARY_MAX = 26;
struct Trie {
private:
int cnt = 0;
int level = 0;
Trie *children[DICTIONARY_MAX] = {};
public:
void insert(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] -> insert(s, position + 1);
}
}
void erase(string s, int position = 0){
--level;
if(s.size() == position) --cnt;
else {
int to = s[position] - 'a';
children[to] -> erase(s, position + 1);
if(!children[to] -> level) {
delete children[to];
children[to] = nullptr;
}
}
}
int count(string s, int position = 0){
if(position == s.size()) return cnt;
int to = s[position] - 'a';
if(!children[to]) return 0;
return children[to] -> count(s, position + 1);
}
int longestCommonPrefix(string s, int position = 0){
if(position == s.size()) return 0;
int to = s[position] - 'a';
if(!children[to]) return 0;
return 1 + children[to] -> longestCommonPrefix(s, position + 1);
}
};
void solve(){
short type;
string word;
Trie *root = new Trie;
while(cin >> type >> word){
if(type == 0){
root -> insert(word);
}
else if(type == 1){
root -> erase(word);
}
else if(type == 2){
cout << root -> count(word) << '\n';
}
else {
cout << root -> longestCommonPrefix(word) << '\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;
}