Addition Chains (zoj-1937)

Addition Chains

An addition chain for n is an integer sequence with the following four properties:

a0 = 1
am = n
a0 < a1 < a2 < … < am-1 < am
For each k (1 <= k <= m) there exist two (not necessarily 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

The input will contain one or more test cases. Each test case consists of one line containing one integer n (1 <= n <= 100). Input is terminated by a value of zero (0) for n.

Output

For each test case, print one line containing the required integer sequence. Separate the numbers by one blank.

Sample Input

5
7
12
15
77
0
Sample Output

1 2 4 5
1 2 4 6 7
1 2 4 8 12
1 2 4 5 10 15
1 2 4 8 9 17 34 68 77

首先题意需要清楚,通过给出的一个不大于100的数字n,要输出一个首项是1其余各项可以由前面任意两项相加可得(ak = ai + aj (0 <= i, j <= k-1))并且尾项是n的这么一个递增数列
而且要使该数列长度最短 答案不唯一 输出其中一个即可

一步一步解题。
1.首先我们需要做的是创造这么一个序列,要去添加序列的每一项,直到n结束我们可以添加的项 为前面任意两项之和。所以我们可以创造一个数组把ai 所有可能取值存进去
2.第二步 我们需要考虑最短的问题,我们可以可以尝试所有可能,保留符合条件且最短的序列但是,时间只有1s,我们需要优化时间复杂度。
3.因为该序列是递增序列,所以要使序列最短,尽可能满足条件下,每次放最大的值,这样我们的ai会越来越接近n;所以我们可以把第三步说的那个数组从大到小排序,这样即可在时间复杂度要求下输出符合条件的最短序列。

完整代码如下:

#include
#include
#define inf 0x3f3f3f3f
using namespace std;
int a[12000],flag,n,minn,c[1010],w[12000];
void dfs(int step)
{
    if(step>=minn) return ;
    if(a[step-1]==n)
    {
        if(step=1; i--)
        for(int j=i; j>=1; j--)
        {
            if(a[i]+a[j]<=a[step-1])break;
             if(a[i]+a[j]<=n)
                  s[k++]=a[i]+a[j];
        }
    sort(s,s+k);
    for(int i=k-1;i>=0;i--)
    {
        a[step]=s[i];
        dfs(step+1);
    }
}
int main()
{
    while(~scanf("%d",&n)&&n)
    {
        minn=0x3f3f3f3f;
        a[1]=1;
        flag=0;
        dfs(2);
        for(int i=1; i

你可能感兴趣的:(Addition Chains (zoj-1937))