题意:输入一个n,问x从1次方开始,到n次方 ,可以乘或除已经计算出来的数 ,最少需要执行多少步?
思路:迭代加深 ,深度从0开始 ,直到返回值为真。 在深搜过程中剪枝(深度的判断 ,当前最大值尽全力是否能到达 n )
代码:
/*迭代加深*/
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define max(a,b) a>b?a:b
int dep,num[15],n;
/*枚举深度 从小到大 */
/*数组记录走过的每一步 深搜*/
bool dfs(int cnt,int x)/*x上一次操作的最大的数*/
{
if(num[cnt]==n)
return 1;
if(cnt>=dep)return 0;
x=max(num[cnt],x);/*计算最大的数*/
if(x*(1<<(dep-cnt))<n)return 0;/*表示最大的数都得不到n 2,4,8,16这样从x增长都得不到*/
for(int i=0;i<=cnt;i++)
{
num[cnt+1]=num[cnt]+num[i];/*表示相乘*/
if(dfs(cnt+1,x))return 1;
num[cnt+1]=abs(num[cnt]-num[i]);/*除法*/
if(dfs(cnt+1,x))return 1;
}
return 0;
}
int main()
{
while(~scanf("%d",&n)&&n)
{
if(n==1)
printf("0\n");
else
{
num[0]=1;
for(dep=0;;dep++)
if(dfs(0,1))break;
printf("%d\n",dep);
}
}
return 0;
}