Pagini recente » Cod sursa (job #470981) | Cod sursa (job #1289475) | Cod sursa (job #2140709) | Cod sursa (job #1932974) | Cod sursa (job #2684703)
#include <bits/stdc++.h>
using namespace std;
struct Node{
Node *son[26];
int ap, sum;
Node()
{
for(int i=0; i<26; ++i) son[i] = nullptr;
ap = 0; sum = 0;
}
void insert(string &S, int pos){
++sum;
if(pos == S.size()){
++ap;
return;
}
int id = S[pos] - 'a';
if(son[id] == nullptr) son[id] = new Node();
son[id] -> insert(S, pos+1);
}
void erase(string &S, int pos){
--sum;
if(pos == S.size()){
--ap;
return;
}
int id = S[pos] - 'a';
son[id] -> erase(S, pos+1);
if(!son[id]->sum){
delete son[id];
son[id] = nullptr;
}
}
int count(string &S, int pos){
if(pos == S.size()) return ap;
int id = S[pos] - 'a';
if(son[id] == nullptr) return 0;
return son[id] -> count(S, pos+1);
}
int longest_prefix(string &S, int pos){
if(pos == S.size()) return pos;
int id = S[pos] - 'a';
if(son[id] == nullptr) return pos;
return son[id] -> longest_prefix(S, pos+1);
}
};
class TRIE{
Node *root;
public:
void init(){
root = new Node();
}
void insert(string &word){
root -> insert(word, 0);
}
void erase(string &word){
root -> erase(word, 0);
}
int count(string &S){
return root -> count(S, 0);
}
int longest_prefix(string &S){
return root->longest_prefix(S, 0);
}
} Trie;
int main()
{
ifstream fin ("trie.in");
ofstream fout ("trie.out");
int type;
string word;
Trie.init();
while(fin >> type >> word){
if(type == 0)
Trie.insert(word);
else if(type == 1)
Trie.erase(word);
else if(type == 2)
fout << Trie.count(word) << '\n';
else fout << Trie.longest_prefix(word) << '\n';
}
return 0;
}