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

poj 2001 Shortest Prefixes 字典树的输出问题的解释~~ 2012-4-14

这是usc的第三周的模拟题赛,讲解的是字典树和kmp(一种动态规划),为ac自动机做充足的准备。

这个字典树代码十分的简单,但自己还是认真的背了一遍又一遍,在dev c++上反复的誊写,直到能够熟练的运用题型的模版~~

第一次默写的模版一遍成功了,但第二次的模版wa了5遍,一直在反复的寻找原因,最后终于找到了,原因是search函数 输出的while循环应该为for循环;

具体情况看代码~~

正确代码:注意代码的风格~~易懂。

#include<stdio.h>
#include<string.h>
#include<malloc.h>
#include<stdlib.h>
void maketire(char temp1[]);
void search(char temp2[]);

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

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

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

void search(char temp2[]){
     structnode *r;
     int len,i;
     r=root;
     len=strlen(temp2);
     for(i=0;i<len;i++){             //我却用while循环替代产生来的错误。
         if(r->next[temp2[i]-'a']!=NULL){
               printf("%c",temp2[i]);
               r=r->next[temp2[i]-'a'];                
               if(r->count==1)break;  
                                              
                                         }                  
                        }  
     }

我错误的地方在于 上文代码标记处~~

void search(char temp2[]){
    int i=0;
     structnode *r=root;
     while(r->next[temp2[i]-'a']!=NULL){   //此处不能用while替代for循环。
       printf("%c",temp2[i]);
       r=r->next[temp2[i]-'a'];
              i++;
       if(r->count==1)break;                                     
                                       }
                      }

举个例子;
例如输入 ab
abc

得出的结果不一样。因为利用while循环会导致while判断b时结果为2,导致得判断第一项中的b后面的'\0'会将 r->next[temp2[i]-'a']!=NULL 中的 temp2[i]用'\0'替代导致错误。
导致输出的结果为
第一行 ab就结束程序了。
下次一定要注意这样的情况。



posted @ 2012-04-14 22:02  大嘴鸟  阅读(248)  评论(0)    收藏  举报
Mastermate官网 香港|英国|新加坡|澳大利亚|澳门|深圳硕士研究生申请平台