Pagini recente » Cod sursa (job #239660) | Cod sursa (job #1241954) | Istoria paginii runda/de_placere/clasament | Cod sursa (job #2220414) | Cod sursa (job #1769737)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
int freq,count;
node * table[27];
};
node * root;
int c;
char * p;
void create(node ** x)
{
*x=(node *) malloc(sizeof(node));
(*x)->freq=0;
(*x)->count=0;
memset((*x)->table,0,sizeof((*x)->table));
}
void add(node ** x,char * p)
{
if (*x==NULL)
create(x);
(*x)->freq++;
if (*p==0)
(*x)->count++; else
add(&((*x)->table[*p-'a']),p+1);
}
void _delete(node ** x, char * p)
{
if (*p==0)
{
if ((*x)->freq==1)
free(*x),*x=0; else
(*x)->freq--,(*x)->count--;
}
else
{
_delete(&(*x)->table[(*p-'a')],p+1);
if ((*x)->freq==1)
free(*x),*x=0; else
(*x)->freq--;
}
}
int count(node * x, char * p)
{
if (x==NULL) return 0;
if (*(p)==0)
return x->count;
return count(x->table[*p-'a'],p+1);
}
int pref(node * x,char * p,int k)
{
//printf("%d %s-- \n",k,p);
if (x==NULL) return k-1;
if (*(p)==0)
return k;
return pref(x->table[*p-'a'],p+1,k+1);
}
int main(int argc, char const *argv[])
{
freopen("trie.in","r",stdin);
freopen("trie.out","w",stdout);
create(&root);
p= (char *) malloc(25*sizeof(char));
while (scanf("%d %s",&c,p)==2)
{
if (c==0)
add(&root->table[*p-'a'],p+1); else
if (c==1)
_delete(&root->table[*p-'a'],p+1); else
if (c==2)
printf("%d\n",count(root->table[*p-'a'],p+1)); else
if (c==3)
printf("%d\n",pref(root->table[*p-'a'],p+1,1));
memset(p,0,25);
}
fclose(stdin);
fclose(stdout);
return 0;
}