Pagini recente » Cod sursa (job #2022389) | Cod sursa (job #2362225) | Cod sursa (job #1677914) | Cod sursa (job #2740344) | Cod sursa (job #2017923)
#include<cstdio>
#include<cstdlib>
#include<cstring>
#define MAX_LENGTH 20
#define SIGMA 26
using namespace std;
struct trieNode
{
int cnt, fin;
struct trieNode* child[SIGMA];
};
struct trieNode* root;
struct trieNode* getNode()
{
struct trieNode* node;
node = (struct trieNode*)malloc(sizeof(struct 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* key)
{
struct trieNode* node = root;
int length = strlen(key);
for(int i=0; i<length; i++)
{
if(node->child[key[i]-'a'] == NULL)
node->child[key[i]-'a'] = getNode();
node = node->child[key[i]-'a'];
++node->cnt;
}
++node->fin;
}
void DeleteWord(struct trieNode* root, char* key)
{
struct trieNode* node = root;
struct trieNode* node2 = root;
int length = strlen(key);
for(int i=0; i<length; i++)
{
node2 = node->child[key[i]-'a'];
--node2->cnt;
if(node2->cnt == 0) node->child[key[i]-'a'] = NULL;
if(node->cnt == 0) free(node);
node = node2;
}
--node2->fin;
}
int SearchWord(struct trieNode* root, char* key)
{
struct trieNode* node = root;
int length = strlen(key);
int i = 0;
while(i < length && node->child[key[i]-'a'] != NULL)
{
node = node->child[key[i]-'a'];
i++;
}
return(i == length? node->fin : 0);
}
int prefixSearch(struct trieNode* root, char* key)
{
struct trieNode* node = root;
int length = strlen(key);
int i, nr;
i = nr = 0;
while(i < length && node->child[key[i]-'a'] != NULL)
{
node = node->child[key[i]-'a'];
i++;
nr++;
}
return nr;
}
int main()
{
char word[MAX_LENGTH+1];
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",&op);
fscanf(fin,"%s\n",word);
if(!op) 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;
}