zoukankan      html  css  js  c++  java
  • 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;
    }
    
    
    

      



  • 相关阅读:
    IE8、IE7、IE6、Firefox2.0.0.12的一些CSS HACK测试
    scrollLeft,scrollWidth,clientWidth,offsetWidth到底指的哪到哪的距离
    使用XML技术实现OWC对数据库的展示
    Server Push详解
    Ajax ReadyState的五种状态详解
    JavaScript 动态创建表格:新增、删除行和单元格
    Windows 7令人满意,Code 7让人失望
    当Outlook 2010 Beta遇上Windows Mobile Device Center 6.1
    实际使用Windows 7中的Readyboost功能
    打开梦想的窗——成都Windows 7社区发布活动和Windows 7 Party总结
  • 原文地址:https://www.cnblogs.com/JYYHH/p/8575914.html
Copyright © 2011-2022 走看看