#include<iostream>
using namespace std;
int n,p,v[1005];
bool ida(int now,int depth){
if(now>depth) return false;
if(v[p]<<(depth-now)<n) return false;//估价函数:用最快的倍增(连续倍增)都不能达到n,直接退出
if(v[p]==n) return true;
p++;
for(int i=0;i<p;i++){
v[p]=v[p-1]+v[i];//上一个数与之前的数相加
if(ida(now+1,depth)) return true;
v[p]=abs(v[p-1]-v[i]);//上一个数与之前的数相减
if(ida(now+1,depth)) return true;
}
p--;//回溯
return false;
}
int main()
{
while(cin>>n&&n)
{
int depth;
//给dfs一个深度的限制
for(depth=0;;depth++){
p=0;
v[0]=1;//初始值为1
if(ida(0,depth)) break;
}
cout<<depth<<endl;
}
return 0;
}
总结:
通过估值函数和设定depth的方式优化dfs,当dfs进行到一定深度时不再继续,提高了效率