梦,才是最真的现实

导航

记忆化搜索 HDU1501

自己想不到啊,原来记忆化也可以当做是剪枝的一部分,有个小发现,用bool类型判断比0 1判断效率高点

#include<stdio.h>
#include<string.h>
#define Max 205
bool memory[Max][Max];
char str1[Max],str2[Max],str3[500];
bool found;
void dfs(int atemp,int btemp,int ptemp);
int main()
{
int n,t;
t=0;
for(scanf("%d",&n);n;n--)
{
found=false;
memset(memory,false,sizeof(memory));
scanf("%s%s%s",str1,str2,str3);
printf("Data set %d: ",++t);
dfs(0,0,0);
if(found) printf("yes\n");
else printf("no\n");
}
return 0;
}
void dfs(int atemp,int btemp,int ptemp)
{
if(found) return ;
if(str3[ptemp]==0)
{
found=true;
return;
}
if(memory[atemp][btemp]) return;//如果已经访问过,无需再访问,因为如果该状态有结果的话,found==true了,也就不会执行这个语句了
memory[atemp][btemp]=true;
if(!found&&str1[atemp]==str3[ptemp])
dfs(atemp+1,btemp,ptemp+1);
if(!found&&str2[btemp]==str3[ptemp])
dfs(atemp,btemp+1,ptemp+1);
return ;
}

posted on 2012-05-21 22:44  梦,才是最真的现实  阅读(135)  评论(0编辑  收藏  举报