Pagini recente » Flux si cuplaj | Cod sursa (job #2810867) | Cod sursa (job #2592225) | Cod sursa (job #2090870) | Cod sursa (job #1997993)
#include<cstdio>
#include<cstring>
#include<cstdlib>
#define SIGMA 26
#define MAX_LEN 20
using namespace std;
struct trie
{
int cnt, fin;
struct trie* child[SIGMA];
};
struct trie* root;
struct trie* getNode()
{
struct trie* node;
node = (struct trie*)malloc(sizeof(struct trie));
node->cnt = node->fin = 0;
for(int i=0; i<SIGMA; i++)
node->child[i] = NULL;
return node;
};
void Insert(struct trie* root, char* key)
{
struct trie* 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 Delete(struct trie* root, char* key)
{
struct trie* node = root;
struct trie* tmp = root;
int length = strlen(key);
for(int i=0; i<length; i++)
{
tmp = node->child[key[i]-'a'];
--tmp->cnt;
if(tmp->cnt == 0) node->child[key[i]-'a'] = NULL;
if(node->cnt == 0) free(node);
node = tmp;
}
--tmp->fin;
}
int Search(struct trie* root, char* key)
{
struct trie* node = root;
int length = strlen(key);
bool ok = true;
for(int i=0; i<length && ok; i++)
{
if(node->child[key[i]-'a'] == NULL)
ok = false;
node = node->child[key[i]-'a'];
}
if(ok) return node->fin;
else return 0;
}
int prefixSearch(struct trie* root, char* key)
{
struct trie* node = root;
int length = strlen(key);
int nr = 0;
bool ok = true;
for(int i=0; i<length && ok; i++)
{
if(node->child[key[i]-'a'] == NULL)
ok = false;
else ++nr;
node = node->child[key[i]-'a'];
}
return nr;
}
int main()
{
char word[MAX_LEN + 1];
int op;
FILE *fin, *fout;
fin = fopen("trie.in","r");
fout = fopen("trie.out","w");
root = getNode();
root->cnt = 11;
while(!feof(fin))
{
fscanf(fin,"%d",&op);
fscanf(fin,"%s\n",word);
if(!op) Insert(root,word);
else if(op == 1) Delete(root,word);
else if(op == 2) fprintf(fout,"%d\n",Search(root,word));
else fprintf(fout,"%d\n",prefixSearch(root,word));
}
fclose(fin);
fclose(fout);
return 0;
}