题意:输入正整数n (1≤n≤1000) ,问最少需要几次乘法除法可以从x得到 xn ?例如 x31 需要6次: x2=x∗x , x4=x2∗x2 , x8=x4∗x4 , x16=x8∗x8 , x32=x16∗x16 , x31=x32/x 。计算过程中x的指数应当总是正整数(如 x−3=x/x4 是不允许的)。(本段摘自《算法竞赛入门经典(第2版)》)
分析:
使用IDA*,deep表示当前深度,maxd表示深度上限,如果当前序列最大的数乘以
2maxd−deep
之后仍小于n,则剪枝。
代码:
#include <iostream>
#include <algorithm>
#include <fstream>
#include <cstring>
using namespace std;
const int maxn = 2000 + 5;
int n, maxm, cnt;
int a[maxn];
int power(int x, int y)
{
int res = 1;
for (int i = 0; i < y; ++i)
res *= x;
return res;
}
bool DFS(int x, int deep, int limit)
{
if (x == n)
return true;
if (deep >= limit)
return false;
if (maxm * power(2, limit - deep) < n)
return false;
for (int i = cnt - 1; i >= 0; --i)
{
int tmp = x + a[i];
int last = maxm;
maxm = max(maxm, tmp);
a[cnt++] = tmp;
if (DFS(tmp, deep + 1, limit))
return true;
maxm = last;
--cnt;
tmp = x - a[i];
a[cnt++] = tmp;
if (DFS(tmp, deep + 1, limit))
return true;
--cnt;
}
return false;
}
int main()
{
while (~scanf("%d", &n), n)
{
for (int maxd = 0; ; ++maxd)
{
maxm = 1;
a[0] = 1;
cnt = 1;
if (DFS(1, 0, maxd))
{
printf("%d\n", maxd);
break;
}
}
}
return 0;
}