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就结束程序了。
下次一定要注意这样的情况。



转载于:https://www.cnblogs.com/ysh-blog/archive/2012/04/14/2447749.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值