uva529
来源:互联网 发布:京东万象数据平台 编辑:程序博客网 时间:2024/04/28 06:45
An addition chain for n is an integer sequence <!-- MATH: $$ --> with the following four properties:
- a0 = 1
- am = n
- a0<a1<a2<...<am-1<am
- For each k ( ) there exist two (not neccessarily different) integersi and j ( ) withak =ai +aj
You are given an integer n. Your job is to construct an addition chain forn 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 integern ( ). Input is terminated by a value of zero (0) forn.
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
经典题目
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
int n,q[100],f[100],m;
int dfs(int h)
{
if(h<m)
{
for(int i=h-1; i>=0; i--)
{
int c=q[i]+q[h-1];
if(c<=n)
{
q[h]=c;
if(c==n&&m>h)
{
for(int j=0; j<=h; j++)
f[j]=q[j];
m=h;
}
else if(c*1<<(m-h-1)>=n)dfs(h+1);
//c*1<<(m-h-1)是指在不超出的情况下c的最大增长
}
}
}
}
int main()
{
while(cin>>n&&n)
{
if(n==1)cout<<1<<endl;
else
{
m=30;
q[0]=1;
dfs(1);
for(int i=0; i<m; i++)
cout<<f[i]<<' ';
cout<<n<<endl;
}
}
return 0;
}
- uva529
- UVA529
- uva529
- UVA529- Addition Chains(迭代+DFS)
- uva529 迭代加深+必要剪枝
- UVA529 Addition Chains (迭代+DFS)
- UVA529加深迭代搜索,起点为1,终点为n,数列中的每个数由前面俩个数的和组成的最短数列
- 学习List之双击显示
- stm32 nvic的理解
- myeclipse+aptana插件安装和破解
- 读”信息资源管理”
- 编写T4模板进行代码生成
- uva529
- 从数据到代码——通过代码生成机制实现强类型编程[上篇]
- Linux --Install Sun Java Runtime
- jQuery代码的14条改善技巧
- asp.net编程中所遇到的问题
- Linux 重启命令
- 从数据到代码——通过代码生成机制实现强类型编程[下篇]
- socket通讯是使用第三方库还是手工封装操作系统api
- 细节决定成败