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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值