UVA 529 Addition Chains
来源:互联网 发布:程序员的硬技能 编辑:程序博客网 时间:2024/05/18 06:13
分析
给定一个数,尝试构造一个最短的数列,每一个数字由其之前的数字相加得,使得最后一个数字为所给数字。
每一次尝试相加其实应该是前一个值尝试加上自它向前的所有值。例如5,尝试1,2,…,下一位应该先尝试4,再尝试3。
这里注意需要剪枝!如何判断能否构造成功呢?
考虑一下上面的尝试方法,最大值是不是它的2倍呢?如果这个值在有限次数的翻倍也不能到达这个数,那么可以不用尝试了。
至于最大长度16个数,还是一个magic number(提交多次试的..当然无妨开大一些的)。
代码
#include <cstdio>#define MAX_N 16int n, p, a[MAX_N] = {1}, r[MAX_N];void dfs(int t){ if (t >= p) return; if (a[t-1] == n) { p = t; for (int i = 0; i < p; i++) r[i] = a[i]; return; } for (int i = t-1; i >= 0; i--) { a[t] = a[t-1] + a[i]; if (a[t] <= n && a[t]<<(p-t-1) >= n) dfs(t + 1); }}void solve(){ p = MAX_N; dfs(1); for (int i = 0; i < p; i++) { printf("%d", r[i]); if (i != p-1) printf(" "); else printf("\n"); }}int main(){ while (scanf("%d", &n), n) solve();}
题目
Description
An addition chain for n is an integer sequence
- a0 = 1
- am = n
- a0< a1< a2<…< am-1< a m
- For each k (
1≤k≤m ) there exist two (not neccessarily different) integers i and j (0≤i,j≤k−1 ) with ak=ai+aj
You are given an integer n. Your job is to construct an addition chain for n with minimal length. If there is more than one such sequence, any one is acceptable.
For example, <1,2,3,5> and <1,2,4,5> are both valid solutions when you are asked for an addition chain for 5.
Input Specification
The input file will contain one or more test cases. Each test case consists of one line containing one integer n (
Output Specification
For each test case, print one line containing the required integer sequence. Separate the numbers by one blank.
Hint: The problem is a little time-critical, so use proper break conditions where necessary to reduce the search space.
Sample Input
571215770
Sample Output
1 2 4 51 2 4 6 71 2 4 8 121 2 4 5 10 151 2 4 8 9 17 34 68 77
- uva 529 - Addition Chains
- uva 529 Addition Chains
- UVA 529 - Addition Chains
- uva 529 - Addition Chains
- UVA 529 Addition Chains
- poj 2248--Addition Chains (uva 529--Addition Chains)
- uva 529 Addition Chains(迭代深搜)
- UVA 529 - Addition Chains 剪枝+迭代深搜
- UVa 529 - Addition Chains ,迭代加深搜索+减枝
- UVA 529 Addition Chains(迭代搜索)
- [UVA 529] Addition Chains (迭代加深搜索)
- UVA - 529 Addition Chains(迭代+dfs)
- UVa 529 POJ 2248 - Addition Chains ,迭代加深搜索+减枝
- poj2248 Addition Chains--------dfs
- HDU Addition Chains
- C - Addition Chains
- poj 2248 Addition Chains
- POJ 2248 Addition Chains
- Android中AsyncTask的简单用法
- Android中几种关闭Activity或app的方法
- 收藏下 Unicode范围
- Linux命令more
- SAP调用webservice 参数为空
- UVA 529 Addition Chains
- 如何给MP4视频加字幕
- UNIX Tutorial Three
- DOM(二)-13-(示例-全选商品列表)
- OCiOS开发:NSURLConnection 网络请求
- Java对象数组
- photoshop制作艺术字视频教学
- Hue3.9 安装教程:华丽的Spark,Hadoop UI
- POJ 3984:迷宫问题【BFS】