Pagini recente » Cod sursa (job #2658176) | Cod sursa (job #2862863) | Cod sursa (job #2408359) | Cod sursa (job #2259547) | Cod sursa (job #2403735)
#include <bits/stdc++.h>
using namespace std;
ifstream f("trie.in");
ofstream g("trie.out");
const int SIGMA = 30;
struct Node{
int prefix;
int words;
Node *nei[SIGMA];
};
int x;
string str;
Node *root;
void add(string str, Node *node){
Node *aux = node;
for(int i = 0; i < str.size(); ++i){
if(nullptr == aux->nei[str[i] - 'a']){
Node *newNode = new Node;
newNode->prefix = 0;
newNode->words = 0;
for(int j = 0; j < SIGMA; ++j){
newNode->nei[j] = nullptr;
}
aux->nei[str[i] - 'a'] = newNode;
}
aux = aux->nei[str[i] - 'a'];
aux->prefix++;
}
aux->words++;
}
void del(string str, Node *node){
Node *aux = node;
for(int i = 0; i < str.size(); ++i){
aux = aux->nei[str[i] - 'a'];
aux->prefix--;
}
aux->words--;
}
int apar(string str, Node *node){
Node *aux = node;
for(int i = 0; i < str.size(); ++i){
if(nullptr == aux->nei[str[i] - 'a']){
return 0;
}
aux = aux->nei[str[i] - 'a'];
}
if(nullptr == aux){
return 0;
}
return aux->words;
}
int lung(string str, Node *node){
Node *aux = node;
int lung = 0;
int mx = 0;
int i = 0;
for(i = 0; i < str.size(); ++i){
if(aux == nullptr){
break;
}
if(aux->prefix != 0){
mx = lung;
}
aux = aux->nei[str[i] - 'a'];
lung ++;
}
if(i == str.size()){
mx ++;
}
return mx;
}
int main(){
root = new Node;
root->prefix = 0;
root->words = 0;
for(int i = 0; i < SIGMA; ++i){
root->nei[i] = nullptr;
}
while(f >> x){
f >> str;
if(x == 0){
add(str, root);
}else if(x == 1){
del(str, root);
}else if(x == 2){
g << apar(str, root) << '\n';
}else if(x == 3){
g << lung(str, root) << '\n';
}
}
return 0;
}