我是靠谱客的博主 辛勤唇彩,最近开发中收集的这篇文章主要介绍问题 D: 【例题4】Addition Chains,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

来源http://poj.org/problem?id=2248 

An addition chain for n is an integer sequence <a0,a1,a2,…,am><a0,a1,a2,…,am> with the following four properties:

a0 = 1

am = n

a0< a1< a2<…< am-1< a m

For each k ( 1≤k≤m1≤k≤m) there exist two (not neccessarily different) integers i and j ( 0≤i,j≤k−10≤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 file will contain one or more test cases. Each test case consists of one line containing one integer n ( 1≤n≤100001≤n≤10000). 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

思路:

这是一道dfs的剪枝,我们可以把第x数看成最大为a[x-1]+a[x-2],那么我们可以每次标记一下最大值,然后还是枚举之前的a[i],然后逐层dfs,最后当得到n后输出数组a[];

代码

#include <iostream> 
#include <cstdio> 
#include <fstream> 
#include <algorithm> 
#include <cmath> 
#include <deque> 
#include <vector> 
#include <queue> 
#include <string> 
#include <cstring> 
#include <map> 
#include <stack> 
#include <set> //吐槽一下poj,万能头不给过 *^* 
using namespace std;
int n,sp,a[10000001];
bool dfs(int x,int y)//x代表此时的长度 ,y代表此时最大值 
{
    if(x==sp)//当长度满足sp时 
    {
        if(a[x-1]==n)//判断是否可以达到n 
        return true;
        else
        return false;
    }
    for(int i=0;i<=x-1;i++)//枚举每一个数 
    {
		for(int j=i;j<=x-1;j++)
        {
            if(a[i]+a[j]>n)//当两个数相加大于要求的数时,证明已经可以得出n 
            break;
            if(a[i]+a[j]>y)//更新最大值 
            {
	           	a[x]=a[i]+a[j];
	            if(dfs(x+1,a[x]))//进行下一层判断 
	            return true; 
            }
        }
	}
    return false;
}
int main()
{
    while(~scanf("%d",&n))
    {
		a[0]=1;//初始化a[0]为1 
    	if(n==0)
    	break;
        for(int i=1;;i++)
        {
            sp=i;//遍历长度 
            if(dfs(1,1))
            {
                for(int j=0;j<=i-1;j++)
                {
                	cout<<a[j]<<" ";
				}
                cout<<endl;
                break;
            }
        }
    }
    return 0;
}

 

最后

以上就是辛勤唇彩为你收集整理的问题 D: 【例题4】Addition Chains的全部内容,希望文章能够帮你解决问题 D: 【例题4】Addition Chains所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(59)

评论列表共有 0 条评论

立即
投稿
返回
顶部