poj 2001 Shortest Prefixes 字典树的输出问题的解释~~ 2012-4-14
2012-04-14 22:02
441 查看
这是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就结束程序了。 下次一定要注意这样的情况。
相关文章推荐
- poj 2001 Shortest Prefixes ——字典树入门
- 字典树---2001 POJ Shortest Prefixes(找最短前缀)
- POJ 2001 Shortest Prefixes【字典树】
- POJ Shortest Prefixes -- 最短前缀问题 -- 字典树
- 字典树---2001 POJ Shortest Prefixes(找最短前缀)
- [复习][poj2001]字典树(trie树)Shortest Prefixes
- Shortest Prefixes POJ - 2001(字典树)
- poj 2001 Shortest Prefixes 【字典树】【找每一个字符串在字符串集里面的 最短且可唯一标识 的前缀】
- POJ 2001 Shortest Prefixes 字典树
- POJ 2001 Shortest Prefixes 【 trie树(别名字典树)】
- POJ 2001-Shortest Prefixes【字典树】
- POJ2001 - Shortest Prefixes - 字典树
- POJ 2001 Shortest Prefixes 字典树Trie
- poj 2001 Shortest Prefixes 字典树
- POJ 2001 Shortest Prefixes【第一棵字典树】
- POJ 2001 Shortest Prefixes 【 trie树(别名字典树)】
- POJ2001 Shortest Prefixes 动态字典树实现
- POJ 2001 Shortest Prefixes【字典树】
- 【POJ 2001 Shortest Prefixes】+ 字典树
- POJ 2001 Shortest Prefixes 字典树经典题,求最短唯一前缀)