您的位置:首页 > 其它

UVa 1374:Power Calculus(IDA*)

2015-09-09 23:39 197 查看
题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=841&page=show_problem&problem=4120

题意:输入正整数n(1≤n≤1000)(1 \le n \le 1000),问最少需要几次乘法除法可以从x得到xnx^n?例如x31x^{31}需要6次:x2=x∗xx^2=x*x,x4=x2∗x2x^4=x^2*x^2,x8=x4∗x4x^8=x^4*x^4,x16=x8∗x8x^{16}=x^8*x^8,x32=x16∗x16x^{32}=x^{16}*x^{16},x31=x32/xx^{31}=x^{32}/x。计算过程中x的指数应当总是正整数(如x−3=x/x4x^{-3}=x/x^4是不允许的)。(本段摘自《算法竞赛入门经典(第2版)》)

分析:

使用IDA*,deep表示当前深度,maxd表示深度上限,如果当前序列最大的数乘以2maxd−deep2^{maxd-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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: