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

      

  • 相关阅读:
    mysql 使用SUM()函数查询时,如果没有任何记录的时候 返回的结果为null
    不重复的有序集合,TreeSet的用法
    spring+springMVC+mybatis项目中 多数据源的配置
    程序的位置和功能划分
    团队合作-如何避免JS冲突
    CSS的常见问题
    函数传参的应用--修改文本的值
    应用自定义属性、索引值实现带略缩图的图片轮播
    PC和手机的区别就是各种各样的屏幕,响应式布局来适应屏幕
    CSS3动画@keyframes
  • 原文地址:https://www.cnblogs.com/PersistFaith/p/4820065.html
Copyright © 2011-2022 走看看