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

      

  • 相关阅读:
    C++泛型指针的正向与逆向循环读取的改进方法
    C++泛型指针的正向与逆向循环读取时报错Expreeeion:vector iterator + offset out of range问题
    模块“Project”的符号未加载
    简单的验证码Winform程序
    Dapper.Database<TDatabase>QueryMultiple()报错
    IE6IE7 div样式做的下拉框被遮住问题
    统计数据库已分组的表数据行数
    linux远程下载文件 的两种方法之 ftp命令和scp命令
    Oracle多表连接查询区别
    小程序(三)
  • 原文地址:https://www.cnblogs.com/PersistFaith/p/4820065.html
Copyright © 2011-2022 走看看