Pagini recente » Cod sursa (job #1663869) | Cod sursa (job #668540) | Autentificare | Cod sursa (job #187870) | Cod sursa (job #2164976)
#include<cstdio>
#include<cstring>
#define MAX_LEN 20
#define SIGMA 26
using namespace std;
struct trieNode {
int cnt, fin;
trieNode* child[SIGMA];
};
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;
}
inline void insertWord(struct trieNode* root, char* word) {
int i, len;
len = strlen(word);
struct trieNode* node = root;
for(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) {
int i, len;
len = strlen(word);
struct trieNode* node = root;
i = 0;
while(i < len && node->child[word[i]-'a'] != NULL) {
node = node->child[word[i]-'a'];
i++;
}
return (i == len ? node->fin : 0);
}
int prefixSearch(struct trieNode* root, char* word) {
int i, len;
len = strlen(word);
struct trieNode* node = root;
i = 0;
while(i < len && node->child[word[i]-'a'] != NULL) {
node = node->child[word[i]-'a'];
i++;
}
return i;
}
void deleteWord(struct trieNode* root, char* word) {
int i, len;
len = strlen(word);
struct trieNode* node = root;
struct trieNode* node2 = root;
for(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() {
char str[MAX_LEN + 2];
int op;
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,str);
if(op == 0)
insertWord(root,str);
else if(op == 1)
deleteWord(root,str);
else if(op == 2)
fprintf(fout,"%d\n",searchWord(root,str));
else fprintf(fout,"%d\n",prefixSearch(root,str));
}
fclose(fin);
fclose(fout);
return 0;
}