The operation of squaring can be appreciably shorten the sequence of multiplications. The following is a way to compute x31 with eight multiplications:
This is not the shortest sequence of multiplications to compute x31. There are many ways with only seven multiplications. The following is one of them:
If division is also available, we can find a even shorter sequence of operations. It is possible to compute x31 with six operations (five multiplications and one division):
This is one of the most efficient ways to compute x31 if a division is as fast as a multiplication.
Your mission is to write a program to find the least number of operations to compute xn by multiplication and division starting with x for the given positive integer n. Products and quotients appearing in the sequence should be x to a positive integer’s power. In others words, x−3, for example, should never appear.
Input
The input is a sequence of one or more lines each containing a single integer n. n is positive and less than or equal to 1000. The end of the input is indicated by a zero.
Output
Your program should print the least total number of multiplications and divisions required to compute xn starting with x for the integer n. The numbers should be written each in a separate line without any superfluous characters such as leading or trailing spaces.
Sample Input
1
31
70
91
473
512
811
953
0
Sample Output
0
6
8
9
11
9
13
12
题意:从1到n的最小转化步数
思路:迭代加深,深度即步数
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
const int MAXN=50+5;
int da[]={1,2,4,8,16,32,64,128,256,512,1024};
int p[MAXN],cnt,D,n;
int MAX(const int a,const int b){ return a>b?a:b;}
bool dfs(int d,int sum)
{
if(d==D)
{
if(sum==n)return 1;
return 0;
}
int i,j;
for(i=cnt-1;i>=0;i--)
{
int max=0;
for(j=0;j<cnt;j++)
max=MAX(max,p[j]);
if((max+sum)<<(D-d-1)<n)return 0;//剪枝,减去一定达不到n的搜索
p[cnt++]=sum+p[i];//加法情况
if(dfs(d+1,sum+p[i]))return 1;
cnt--;
if(sum-p[i]>0)
{
p[cnt++]=sum-p[i];//减法情况
if(dfs(d+1,sum-p[i]))return 1;
cnt--;
}
}
return 0;
}
int solve(int x)
{
int i;
for(i=0;i<=10;i++)
if(da[i]>=x){D=i;break;}
while(1)
{
memset(p,0,sizeof(p));
p[0]=1;cnt=1;
if(dfs(0,1))break;
D++;
}
return D;
}
int main()
{
while(~scanf("%d",&n),n)
{
printf("%d\n",solve(n));
}
return 0;
}