Cod sursa(job #1769211)

Utilizator dodecagondode cagon dodecagon Data 2 octombrie 2016 10:48:11
Problema Trie Scor 5
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#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 (*p==0)
   	 return; 

   	if (x->table[(*p-'a')]==0)
   		 create(&(x->table[(*p-'a')]));

   	x->freq++;

   	if (*(p+1)==0)
   		x->count++; else 
   	      add(x->table[(*p-'a')],p+1);
}

void _delete(node ** x, char * p) 
{
  if (*p==0)
  	 return ;

   _delete(&(*x)->table[(*p-'a')],p+1);
 
   if ((*x)==root)
   	 (*x)->freq--; else 
   	{

	   if ((*x)->freq==1)
	   	  free(*x),*x=0;
	   	    else 
	   	     {
	   	     	if (*(p+1)==0)
	   	     		(*x)->count--;
	   	     	(*x)->freq--;
	   	     }
   	 }
}

int count(node * x, char * p)
{
	if (x==NULL)  return 0;

    if (*(p+1)==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+1)==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));

     //add(root,"lac");
     //printf("%d\n",pref(root,"latitudine",0));
     //printf("%d\n",count(root,"lac"));

     while (scanf("%d %s",&c,p)>0)
     {
       if (c==0)
       	add(root,p); else 
       if (c==1)
       	_delete(&root,p); else 
       if (c==2)
       	 printf("%d\n",count(root,p)); else 
       if (c==3)
       	printf("%d\n",pref(root,p,0));
       memset(p,0,25);
     }

     


	return 0;
}