• 数列


    问题描述

    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.

    输入

    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.

    输出

    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. 

    样例输入

    5
    7
    12
    15
    77
    0
    

    样例输出

    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
    题意:输入一个数字n,输出一个数列,要求数列的第一个为1,后面的由前面的数字是前面数字中人选两个想家的和,可以选两个相同的数字,亦即对于任意i和j (0<=i, j<=k-1) 有 ak=ai+aj,输出长度最短的一个序列。
    #include <cstdio>
    #include <queue>
    #include <cmath>
    #include <cstring>
    #include <cstdlib>
    #include <iostream>
    #include <algorithm>
    using namespace std;
    const int oo = 0x3f3f3f3f;
    const int N = 200002;
    const int M = 6000;
    typedef long long LL;
    int ac[N] = {1, 2}, QQ[N] = {1, 2}, n, minlen;
    void dfs(int len, int sum)
    {
        int i;
        if(len > minlen || sum > n) return ;
        if(sum == n)
        {
            if(len < minlen)
            {
                minlen = len;
                for(i = 2; i < minlen; i++)
                    QQ[i] = ac[i];
            }
            return ;
        }
        for(i = len-1; i >= 0; i--)
        {
            ac[len] = ac[i] + ac[len-1];
            dfs(len + 1, ac[len]);
        }
    }
    int main()
    {
        int i;
        while(scanf("%d", &n), n)
        {
            if(n == 1)
            {
                printf("1
    ");
                continue;
            }
            minlen = oo;
            dfs(2, 2);
            printf("%d", QQ[0]);
            for(i = 1; i < minlen; i++)
                printf(" %d", QQ[i]);
            printf("
    ");
        }
        return 0;
    }
    

      

  • 相关阅读:
    深入理解虚拟机、容器和Hyper技术
    Hyper:基于Hypervisor的容器化解决方案
    iSCSI 在Linux下的模拟实验
    C-RAN
    spring mvc
    DUBBO
    ajax跨域请求 小栗子 jsonP
    freemarker 页面静态化 简单小栗子
    ajax上传图片监听
    代码优化 粘贴
  • 原文地址:https://www.cnblogs.com/PersistFaith/p/4820065.html
Copyright © 2020-2023  润新知