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,则剪枝。
代码:
题意:输入正整数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; }
相关文章推荐
- XHTML清单
- [算法] 大整数加减乘除法
- MySQL管理员珍藏:十大必备工具盘点
- 数据结构之哈夫曼树
- Java 万年历输出方法
- Linxu 文本处理三剑客
- 【github】2015.09.09 linux 命令行设置代理,连接github(Linux command line set http proxy for connecting github)
- Codeforces Round #318 (Div. 2) E - Bear and Drawing
- 贪吃蛇java源代码做了一些变动自己改名为“我要变胖”
- linux安装teamviewer
- 原始套接字1(Raw Socket)
- 数据结构之线索二叉树
- C++11中的std::bind
- jquery 获取radio
- springMVC+mybatis+ehcache详细配置
- 多线程总结知识点
- java的构造函数
- CSDN文章搜索方法
- OpenGL中的 glVertexAttribPointer 规格化 数据
- ObjC 记录_by jiang_ss 20150908