Addition Chains (zoj-1937)

Addition Chains

An addition chain for n is an integer sequence <a0, a1,a2,…,am> 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<stdio.h>
#include<algorithm>
#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<minn)
        {
            minn=step;
            for(int i=1; i<step; i++)
                w[i]=a[i];
        }
        return ;
    }
    int s[1010],k=0;
    for(int i=step-1; i>=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<minn-1; i++)
            printf("%d ",w[i]);
        printf("%d\n",w[minn-1]);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值