Pagini recente » Cod sursa (job #592388) | Cod sursa (job #428150) | Cod sursa (job #2319408) | Cod sursa (job #2101862) | Cod sursa (job #772365)
Cod sursa(job #772365)
#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
struct NodeTrie {
int V;
NodeTrie* ntr[28];
NodeTrie() {
V = 0;
for(int i = 0; i < 26; i++)
ntr[i] = 0;
}
};
NodeTrie* rTrie;
void insertWordInTrie(NodeTrie* root, char* word, int len) {
if(len == 0) {
root->V++;
return;
}
if(root->ntr[word[0]-'a'] == 0) {
root->ntr[word[0]-'a'] = new NodeTrie();
}
insertWordInTrie(root->ntr[word[0]-'a'], word + 1, len - 1);
}
void deleteWordFromTrie(NodeTrie*& root, char* word, int len) {
if(len == 0) {
int k = 0;
for(int i = 0; i < 26; i++)
if(root->ntr[i] != 0) k++;
root->V--;
if(k == 0 && root -> V == 0) {
delete root;
root = 0;
}
return;
}
deleteWordFromTrie(root->ntr[word[0]-'a'], word + 1, len - 1);
int k = 0;
for(int i = 0; i < 26; i++)
if(root->ntr[i] != 0) k++;
if(k == 0 && root -> V == 0) {
delete root;
root = 0;
}
}
int howManyInTrie(NodeTrie* root, char* word, int len) {
if(root == 0) return 0;
if(len == 0) return root->V;
return howManyInTrie(root->ntr[word[0]-'a'], word + 1, len - 1);
}
int longestPrefix(NodeTrie* root, char* word, int len) {
if(root == 0) return -1;
if(len == 0) return 0;
return 1 + longestPrefix(root->ntr[word[0]-'a'], word + 1, len - 1);
}
int main() {
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
rTrie = new NodeTrie();
int ps = 0;
while(!feof(stdin)) {
int codop;
ps++;
char word[25];
scanf("%d %s",&codop, &word);
if(feof(stdin)) break;
int lung = strlen(word);
if(codop == 0) {
insertWordInTrie(rTrie, word, lung);
}
else
if(codop == 1) {
deleteWordFromTrie(rTrie, word, lung);
}
else
if(codop == 2) {
printf("%d\n",howManyInTrie(rTrie, word, lung));
}
else
if(codop == 3) {
printf("%d\n",longestPrefix(rTrie, word, lung));
}
}
return 0;
}