poj 2248 Addition Chains dfs
啊!蛋都碎了..
输入1的时候,貌似进入了死循环,一直TLE,害得我绞尽脑汁的想该怎么剪枝..
又是一道对层数进行限制的dfs,这种dfs好怪,思路是bfs嘛
View Code
#include <stdio.h>
#include <string.h>
int n,depth,vis[105],ans[105];
int dfs(int k,int a)
{
int i;
if (depth==k)
{
if(a==n)return 1;
return 0;
}
for (i=k;i>=0;i--)
{
a+=ans[i];
if(!vis[a]&&a<=n)
{
ans[k+1]=a;
vis[a]=1;
if(dfs(k+1,a))return 1;
vis[a]=0;
}
a-=ans[i];
}
return 0;
}
int main()
{
int i;
while (scanf("%d",&n)&&n)
{
if(n==1)
{
printf("1\n");continue;
}
ans[0]=1;
for (i=1;;i++)
{
memset(vis,0,sizeof(vis));
depth=i;
if(dfs(0,1))break;
}
for (i=0;i<=depth;i++)
{
printf("%d ",ans[i]);
}
printf("\n");
}
return 0;
}