Mastermate官网 香港|英国|新加坡|澳大利亚|澳门|深圳硕士研究生申请平台

杭电1251题 对于字典树的理解第二节 2012 4-14

刚才开的悲剧的数组,做了杭电1251题才知道,原来字典树可以开始不用开数组的,直接读一个处理一个,***这得根据题意来进行判断***例如poj,必须得先开数组才能进行之后的判断,但对于杭电的1251题来讲,没有告诉数据量的大小,所以需要开一个处理一个,如果直接开数组的话这就是直接碰运气的。

利用代码来进行实现:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

structnode{
        structnode  *next[27];   
        int count;
           }*root;

void maketire(char temp1[]);
void search(char temp2[]);

int main()
{
   char temp[30000][12];
   char temp1[30000][12];
   int i,sum=0,len;
   root=(structnode *)malloc(sizeof(structnode));     
   for(i=0;i<26;i++)
   root->next[i]=NULL;
   root->count=0;
   while(gets(temp[sum])&&temp[sum][0]!='\0')
   
    sum++;                        
   for(i=0;i<sum;i++)
   maketire(temp[i]);
   sum=0;
   while(scanf("%s",temp1[sum])!=EOF)
   sum++;
   
   for(i=0;i<sum;i++){                  
   search(temp1[i]);
   printf("\n");                           
                      }   


}



void maketire(char temp1[]){
     structnode *r,*temp;
     int len,i,j;
     len=strlen(temp1);
     r=root;
     for(i=0;i<len;i++){
            if(r->next[temp1[i]-'a']==NULL){
               temp=(structnode *)malloc(sizeof(structnode));   
                for(j=0;j<26;j++){
                       temp->next[j]=NULL;           
                                  }                            
                     temp->count=0;
                 r->next[temp1[i]-'a']=temp;                           
                                            }   
       r=r->next[temp1[i]-'a'];
       r->count++;                                              
                        }
                     }

void search(char temp2[]){
    int i=0,len;
     structnode *r=root; 
     len=strlen(temp2);     
     for(i=0;i<len;i++)            {
     if(r->next[temp2[i]-'a']!=NULL)  {
       r=r->next[temp2[i]-'a'];
       if(i==len-1){printf("%d",r->count);break;}       
                  }  
     else  {printf("0");break;}                         
                                   }
                      }
posted @ 2012-04-14 23:36  大嘴鸟  阅读(267)  评论(0编辑  收藏  举报
Mastermate官网 香港|英国|新加坡|澳大利亚|澳门|深圳硕士研究生申请平台