问题 D: 【例题4】Addition Chains

本文探讨了如何通过深度优先搜索(DFS)算法构建最短的加法链,以达到给定的整数n。加法链是一种整数序列,其中每个元素都是前两个元素的和,最终达到目标数n,且序列长度最小。文章提供了详细的算法思路和C++实现代码,包括剪枝优化以提高效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值