Addition Chains

https://loj.ac/problem/10021

题目描述

  有这样一个数列\(A\),满足\(a_k = a_i + a_j (0≤ i ,j≤k - 1,i、j可以相等)\)\(a_0 = 1\),求最短长度的序列使该序列的最后一项值为\(n\)

思路

  这道题是纯粹的搜索题,不过唯一的优化就是改变搜索顺序,为了尽快得到\(n\),我们肯定要从大到小进行搜索。不过还有一个方面可以优化就是用迭代加深搜索,限定搜索的深度。不过这道题个人觉得并没有太大意义,因为序列长度是可以直接知道的。在长度为\(m\)的序列中最后一个数最大为\(2^m\)

代码

#include <bits/stdc++.h>
using namespace std;
int n,a[110],cnt,ans[110];
void dfs(int dep)
{
    if(dep>cnt)return ;
    if(a[dep-1]>n)return ;
    if(a[dep-1]==n)
    {
        cnt=dep-1;
        for(int i=1;i<=cnt;i++)
            ans[i]=a[i];
        return ;
    }
//    cout<<k<<' '<<dep<<' '<<n<<endl;
    for(int i=dep-1;i>0;i--)
        if(a[dep-1]+a[i]<=n)
        {
            a[dep]=a[i]+a[dep-1];
            dfs(dep+1);
            a[dep]=0;
        }
}
int main() 
{
    while(scanf("%d",&n))
    {
        if(n==0)break ;
        a[1]=1;cnt=0x7fffffff;
        dfs(2);
        for(int i=1;i<=cnt;i++)
            printf("%d ",ans[i]);
        printf("\n");
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/fangbozhen/p/11760630.html