迭代深搜

给定初始的x,可以通过乘法将其变为x^2,再变为x^4,x^8,x^16,x^32,也可以用除法,x^31 = x^32 / x,但是操作数必须是已经计算出来的数,给定一个指数,要求得到这个指数的最小步数。比如31输出6(1 2 4 8 16 32 31).

n<=1000

#include<bits/stdc++.h>
using namespace std;
int n,h,a[1010];
bool dfs(int x,int cnt)
{
if(x<<(h-cnt)<n)
return 0;
if(cnt>h)
return 0;
a[cnt]=x;
if(x==n)
{
return 1;
}
for(int i=0;i<=cnt;i++)
{
if(dfs(x+a[i],cnt+1))return 1;
if(dfs(abs(x-a[i]),cnt+1))return 1;
}
return 0;
}
int main()
{
while(cin>>n&&n)
{
h=0;
memset(a,0,sizeof(a));
while(!dfs(1,0))
{
memset(a,0,sizeof(a));
h++;
}
cout<<h<<endl;
}
}

原文地址:https://www.cnblogs.com/fanhao050109/p/10886397.html