编程语言
首页 > 编程语言> > Acwing 170. 加成序列(迭代加深算法)

Acwing 170. 加成序列(迭代加深算法)

作者:互联网

170. 加成序列 - AcWing题库

以1开头以n结尾,且每个数是前面任意两数之和的序列的最短长度


        这里迭代加深的层数实际上就是序列的长度,由于求的是最短长度,正好就是迭代加深的目的(解在比较浅的层)

        在处理第u个数时,从前u-1个数找两数之和,由于序列是递增的,为了使序列更小,从较大的和开始枚举,同时判重避免重复无效搜索

#include<iostream>
#include<cstring>
using namespace std;
const int N=105;
int path[N];//序列 
int n;
bool dfs(int u,int depth)
{
    if(u>depth) return false;
    if(path[u-1]==n) return true;
    bool st[N]={0};
    for(int i=u-1;i>=0;i--)
        for(int j=i;j>=0;j--)
        {
            int s=path[i]+path[j];
            if(s>n) continue;
            if(s<=path[u-1]) continue;
            if(st[s]) continue;
            path[u]=s;
            st[s]=true;
            if(dfs(u+1,depth)) return true;
        }
    return false;
}
int main()
{
    path[0]=1;
    while(cin>>n&&n)
    {
        int depth=1;
        while(!dfs(1,depth)) depth++;
        for(int i=0;i<depth;i++)
            cout<<path[i]<<" ";
        cout<<endl;
    }
}

标签:迭代,int,depth,序列,path,Acwing,两数,170
来源: https://blog.csdn.net/weixin_50533561/article/details/123029676