Pagini recente » Cod sursa (job #308065) | Cod sursa (job #619026) | Cod sursa (job #1725593) | Cod sursa (job #132788) | Cod sursa (job #392215)
Cod sursa(job #392215)
#include <stdio.h>
#include <string.h>
struct Trie
{
Trie *next['z'-'a'];
int info;
int ncopii;
Trie()
{
int i;
memset(next, 0, sizeof(next));
info = ncopii = 0;
}
}*r;
void insert(Trie *root, char *word)
{
if(*word == NULL)
{
++(root -> info);
return;
}
if(root->next[*word - 'a'] == NULL)
{
root->next[*word - 'a'] = new Trie;
++(root->ncopii);
}
insert(root->next[*word - 'a'], word + 1);
}
int del(Trie *root, char *a)
{
if(*a == NULL) root -> info--;
else if(del(root->next[*a - 'a'], a+1))
{
root->next[*a - 'a'] = NULL;
root->ncopii --;
}
if(root -> ncopii == 0 && root->info == 0 && root != r)
{
delete root;
return 1;
}
return 0;
}
int count(Trie *root, char *a)
{
if(root == NULL) return 0;
if(*a == NULL) return root->info;
return count(root->next[*a - 'a'], a + 1);
}
int prefix(Trie *root, char *a, int nr)
{
if(*a == NULL || root->next[*a - 'a'] == NULL) return nr;
return prefix(root->next[*a - 'a'], a+1, nr+1);
}
int main()
{
freopen("trie.in", "r", stdin);
freopen("trie.out", "w", stdout);
Trie *t = NULL;
r = new Trie;
while(!feof(stdin))
{
int oper;
char a[25];
scanf("%d %s\n", &oper, a);
if(oper == 0) insert(r, a);
else if(oper == 1) del(r, a);
else if(oper == 2) printf("%d\n", count(r, a));
else if(oper == 3) printf("%d\n", prefix(r, a, 0));
}
return 0;
}