因为n只有1000,再加上是2的k次幂的形式,所以深度不大。
很明显的迭代加深,加个A*剪枝就能秒出样例,700+ms,代码很短。
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<vector>
#include<map>
using namespace std;
int deep,n;
int v[1005]={1};
int h(int top)
{
int k=deep-top;
int x=v[top];
while(k--) x<<=1;
return x;
}
bool dfs(int top)
{
if(v[top-1]==n) return true;
if(top-1>=deep||h(top-1)<n) return false;
for(int i=0;i<top;i++)
{
v[top]=v[i]+v[top-1];
if(dfs(top+1)) return true;
v[top]=abs(v[i]-v[top-1]);
if(dfs(top+1)) return true;
}
return false;
}
int main()
{
while(scanf("%d",&n)&&n)
{
deep=1;
if(n==1) deep=0;
else
while(1)
{
if(dfs(1)) break;
deep++;
}
printf("%d\n",deep);
}
return 0;
}