Pagini recente » Cod sursa (job #957912) | Clasament Teme Pregatire ACM Unibuc 2014, Anul II | Cod sursa (job #2533896) | Cod sursa (job #3242719) | Cod sursa (job #2615520)
#include <bits/stdc++.h>
using namespace std;
class Trie {
private:
struct Node{
int count;
Node* next[26];
Node* father;
Node(Node* father_ = nullptr): count(0), father(father_) {
for (int i=0; i<26; i++)
next[i] = nullptr;
}
~Node(){
count = 0;
for (int i=0; i<26; i++)
next[i] = nullptr;
father = nullptr;
}
} *root;
bool is_deleteable(Node* node){
bool flag = (node->count > 0);
for (int i=0; i<26; i++){
flag |= (node->next[i] != nullptr);
}
return !flag;
}
public:
Trie(): root(new Node()) {}
void insert(string word) {
Node* current_node = root;
unsigned i = 0;
while (i < word.size()){
if (current_node->next[word[i] - 'a'] == NULL){
current_node->next[word[i] - 'a'] = new Node(current_node);
}
current_node = current_node->next[word[i] - 'a'];
i++;
}
current_node->count++;
}
void erase(string word){
Node* current_node = root;
unsigned i = 0;
while (i < word.size()){
current_node = current_node->next[word[i] - 'a'];
i++;
}
current_node->count--;
while (is_deleteable(current_node)){
Node* aux = current_node->father;
for (i=0; i<26; i++){
if (aux->next[i] == current_node)
aux->next[i] = nullptr;
}
delete current_node;
current_node = aux;
}
}
int count_appearences(string word) {
Node * current_node = root;
unsigned i = 0;
while (i < word.size()){
if (!current_node->next[word[i] - 'a'])
return 0;
current_node = current_node->next[word[i] - 'a'];
i++;
}
return current_node->count;
}
int lcs(string word){
Node * current_node = root;
unsigned i = 0;
while (i < word.size()){
if (current_node->next[word[i] - 'a'] == nullptr)
break;
current_node = current_node->next[word[i] - 'a'];
i++;
}
return i;
}
};
int main(){
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
ifstream cin ("trie.in");
ofstream cout ("trie.out");
Trie t;
int o; string s;
while (cin >> o >> s){
if (o == 0) t.insert(s);
else if (o == 1) t.erase(s);
else if (o == 2) cout << t.count_appearences(s) << '\n';
else cout << t.lcs(s) << '\n';
}
return 0;
}