uva529

来源:互联网 发布:京东万象数据平台 编辑:程序博客网 时间:2024/04/28 06:45

  Addition Chains 

An addition chain for n is an integer sequence <!-- MATH: $$ -->$<a_0, a_1, a_2, \dots, a_m>$ with the following four properties:

  • a0 = 1
  • am = n
  • a0<a1<a2<...<am-1<am
  • For each k ( $1 \le k \le m$) there exist two (not neccessarily different) integersi and j ( $0 \le i, j \le k-1$) 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 ( $1 \le n \le 10000$). 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;
}

原创粉丝点击