• Poj 2248 Addition Chains


    Discription
    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. 
    Hint: The problem is a little time-critical, so use proper break conditions where necessary to reduce the search space. 

    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


    这个数列增长最快的话是可以到指数级别的,而n只有400.
    所以我们考虑一下迭代加深。
    但是这样还不够,我们还可以钦定数列单调不减,因为如果有下降的话那么那个降的数不可能是从比它大的转移过来的,所以交换一下就好了。
    还有我们可以从大到小枚举前面的数,可以更快的达到N。

    #include<iostream>
    #include<cstdio>
    #include<cstdlib>
    #include<cstring>
    #include<algorithm>
    #include<cmath>
    #define ll long long
    using namespace std;
    int n,t,a[233];
    
    bool dfs(int x){
    	if(x==t){
    		for(int i=x-1;i;i--)
    		    for(int j=i;j;j--) if(a[i]+a[j]==n){
    		    	a[x]=n;
    		    	return 1;
    			}
    		return 0;
    	}
    	
    	for(int i=x-1;i;i--)
    	    for(int j=i;j;j--) if(a[i]+a[j]>=a[x-1]){
    	    	a[x]=a[i]+a[j];
    	    	if(dfs(x+1)) return 1;
    		}
    	return 0;
    }
    
    int main(){
    	a[1]=1,a[2]=2;
    	while(scanf("%d",&n)==1&&n){
    		if(n==1) puts("1");
    		else if(n==2) puts("1 2");
    		else{
    			for(t=3;;t++) if(dfs(3)){
    				for(int i=1;i<=t;i++) printf("%d ",a[i]);
    				puts("");
    				break;
    			}
    		}
    	}
    	return 0;
    }
    
    
    

      



  • 相关阅读:
    python学习笔记二--列表
    python学习笔记一--字符串
    写点什么呢
    nagios&pnp4nagios--yum 安装
    敏捷开发的思路
    Foreman--管理PuppetClient
    url编码解码的问题(urlencode/quote)
    json数据的处理和转化(loads/load/dump/dumps)
    http和https的区别
    python中requests的用法总结
  • 原文地址:https://www.cnblogs.com/JYYHH/p/8575914.html
Copyright © 2020-2023  润新知