Pagini recente » Cod sursa (job #2322919) | Cod sursa (job #2305637) | Cod sursa (job #2393532) | Cod sursa (job #2572078) | Cod sursa (job #2174487)
#include <bits/stdc++.h>
FILE *fin = freopen("trie.in", "r", stdin);
FILE *fout = freopen("trie.out", "w", stdout);
using namespace std;
const int SIGMA = 26;
struct Trie{
int w_app, p_app;
Trie* sons[SIGMA];
};
Trie* New(){
Trie* node = new Trie;
node->w_app = node->p_app = 0;
for(int i = 0; i < SIGMA; ++ i)
node->sons[i] = NULL;
return node;
}
void Insert(Trie* node, char* w){
if(*w == 0){
node->w_app++;
return;
}
int ch = *w - 'a';
if(node->sons[ch] == NULL)
node->sons[ch] = New();
node = node->sons[ch];
node->p_app ++;
Insert(node, w + 1);
}
void Erase(Trie* node, char *w){
if(*w == 0){
node->w_app--;
return;
}
node = node->sons[*w-'a'];
node->p_app--;
Erase(node, w + 1);
}
int W_app(Trie* node, char* w){
if(*w == 0)
return node->w_app;
if(node->sons[*w-'a'] == NULL)
return 0;
W_app(node->sons[*w-'a'], w + 1);
}
int L_pref(Trie* node, char* w, int length){
if(*w == 0)
return length;
node = node->sons[*w-'a'];
if(node != NULL && node->p_app > 0)
return L_pref(node, w + 1, length+1);
else return length;
}
int main(){
int t;
char word[SIGMA];
Trie* root = New();
while(scanf("%d ", &t) == 1){
gets(word);
if(t == 0)
Insert(root, word);
if(t == 1)
Erase(root, word);
if(t == 2)
printf("%d\n", W_app(root, word));
if(t == 3)
printf("%d\n", L_pref(root, word, 0));
}
return 0;
}