zoukankan      html  css  js  c++  java
  • 数列

    问题描述

    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;
    }
    

      

  • 相关阅读:
    phpstorm Failed to create JVM:error code -4
    php内置函数
    多少
    php 正则
    php 数组 array
    位运算题
    c标准库函数 strcat
    strcpy c标准库函数
    编写一个删除c语言程序文件中所有的注释语句
    杂记
  • 原文地址:https://www.cnblogs.com/PersistFaith/p/4820065.html
Copyright © 2011-2022 走看看