Pagini recente » Cod sursa (job #2619530) | Cod sursa (job #991447) | Cod sursa (job #914895) | Cod sursa (job #1337520) | Cod sursa (job #392144)
Cod sursa(job #392144)
#include <stdio.h>
struct Trie
{
Trie *next['z'-'a'];
int info;
int ncopii;
Trie()
{
int i;
for(i = 0; i <= 'z'-'a'; ++i)
next[i] = NULL;
info = ncopii = 0;
}
}*Root;
Trie* insert(Trie *root, char *word)
{
if(root == NULL) root = new Trie();
if(*word == NULL)
{
++(root -> info);
return root;
}
++(root->ncopii);
root->next[*word - 'a'] = insert(root->next[*word - 'a'], word + 1);
return root;
}
Trie* del(Trie *root, char *a)
{
if(root == NULL) return root;
if(*a == NULL)
{
if(root -> info <= 0) return root;
root -> info--;
if(root->info == 0 && root->ncopii == 0)
{
delete root;
return NULL;
}
return root;
}
if((root->next[*a - 'a'] = del(root->next[*a - 'a'], a+1)) == NULL)
{
--(root->ncopii);
if(root->info == 0 && root->ncopii == 0)
{
delete root;
return NULL;
}
return root;
}
return root;
}
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(root == NULL || *a == NULL) return nr - 1;
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;
Root = new Trie();
while(!feof(stdin))
{
int oper;
char a[25];
scanf("%d %s\n", &oper, a);
if(oper == 0) Root = insert(Root, a);
else if(oper == 1) Root = del(Root, a);
else if(oper == 2) printf("%d\n", count(Root, a));
else if(oper == 3) printf("%d\n", prefix(Root, a, 0));
}
return 0;
}