Pagini recente » Cod sursa (job #2389809) | Cod sursa (job #1233614) | Cod sursa (job #3282685) | Cod sursa (job #2154552) | Cod sursa (job #2258990)
#include "vector"
#include "string"
#include "iostream"
#include "fstream"
using namespace std;
const int SIGMA = 30;
class Trie{
public:
Trie(){
_root = new Node;
_root->value = 0;
for(int i = 0; i < SIGMA; ++i){
_root->edge[i] = nullptr;
}
}
void Add(string word){
_Add(word);
}
void Delete(string word){
_Delete(word);
}
int GetCount(string word){
return _GetCount(word);
}
int LongestPrefix(string word){
return _LongestPrefix(word);
}
private:
void _Add(string word){
Node *current_node = _root;
for(int i = 0; i < word.size(); ++i){
if(current_node->edge[word[i] - 'a'] == nullptr){
Node *aux = new Node;
aux->value = 0;
for(int j = 0; j < SIGMA; ++j){
aux->edge[j] = nullptr;
}
current_node->edge[word[i] - 'a'] = aux;
}
current_node = current_node->edge[word[i] - 'a'];
current_node->prefix++;
}
current_node->value++;
}
void _Delete(string word){
Node *current_node = _root;
for(int i = 0; i < word.size(); ++i){
current_node = current_node->edge[word[i] - 'a'];
current_node->prefix--;
}
current_node->value--;
}
int _GetCount(string word){
Node *current_node = _root;
for(int i = 0; i < word.size(); ++i){
if(current_node->edge[word[i] - 'a'] == nullptr){
return 0;
}
current_node = current_node->edge[word[i] - 'a'];
}
return current_node->value;
}
int _LongestPrefix(string word){
int lung = 0;
Node *current_node = _root;
for(int i = 0; i < word.size(); ++i){
if(current_node->edge[word[i] - 'a'] == nullptr ||
(current_node->edge[word[i] - 'a']->prefix <= 0)){
return lung;
}
current_node = current_node->edge[word[i] - 'a'];
if(current_node != _root){
lung++;
}
}
return lung;
}
struct Node{
int value;
int prefix;
Node *edge[SIGMA];
};
Node *_root;
};
int main(){
ifstream cin("trie.in");
ofstream cout("trie.out");
int x;
Trie *trie = new Trie;
while(cin >> x){
string t;
cin >> t;
if(x == 0){
trie->Add(t);
}else if(x == 1){
trie->Delete(t);
}else if(x == 2){
cout << trie->GetCount(t) << '\n';
}else if(x == 3){
cout << trie->LongestPrefix(t) << '\n';
}
}
return 0;
}