Pagini recente » Cod sursa (job #2345069) | Cod sursa (job #2811614) | Cod sursa (job #2968691) | Cod sursa (job #223654) | Cod sursa (job #2201065)
#include<cstdio>
#include<cstring>
#define MAX_LEN 20
#define SIGMA 26
using namespace std;
struct trieNode {
int cnt, fin;
trieNode* child[SIGMA];
};
struct trieNode* root;
struct trieNode* getNode() {
struct trieNode* node = new trieNode;
node->cnt = node->fin = 0;
for(int i = 0; i < SIGMA; i++)
node->child[i] = NULL;
return node;
}
void insertWord(struct trieNode* root, char* word) {
struct trieNode* node = root;
int len = strlen(word);
for(int i = 0; i < len; i++) {
if(node->child[word[i]-'a'] == NULL)
node->child[word[i]-'a'] = getNode();
node = node->child[word[i]-'a'];
++node->cnt;
}
++node->fin;
}
int searchWord(struct trieNode* root, char* word) {
struct trieNode* node = root;
int len = strlen(word);
int i = 0;
while(i < len && node->child[word[i]-'a'] != NULL) {
node = node->child[word[i]-'a'];
i++;
}
if(i == len)
return node->fin;
return 0;
}
int prefixSearch(struct trieNode* root, char* word) {
struct trieNode* node = root;
int len = strlen(word);
int i = 0;
while(i < len && node->child[word[i]-'a']) {
node = node->child[word[i]-'a'];
i++;
}
return i;
}
void deleteWord(struct trieNode* root, char* word) {
struct trieNode* node = root;
struct trieNode* node2 = root;
int len = strlen(word);
for(int i = 0; i < len; i++) {
node2 = node->child[word[i]-'a'];
--node2->cnt;
if(node2->cnt == 0)
node->child[word[i]-'a'] = NULL;
if(node->cnt == 0)
delete node;
node = node2;
}
--node2->fin;
}
int main() {
int op;
char word[MAX_LEN+2];
FILE* fin, *fout;
fin = fopen("trie.in","r");
fout = fopen("trie.out","w");
root = getNode();
root->cnt = 1;
while(!feof(fin)) {
fscanf(fin,"%d%s\n",&op,word);
if(op == 0)
insertWord(root,word);
else if(op == 1)
deleteWord(root,word);
else if(op == 2)
fprintf(fout,"%d\n",searchWord(root,word));
else fprintf(fout,"%d\n",prefixSearch(root,word));
}
fclose(fin);
fclose(fout);
return 0;
}