zoukankan      html  css  js  c++  java
  • Acwing 170 加成序列 (迭代加深搜索)

    题面

    满足如下条件的序列X(序列中元素被标号为1、2、3…m)被称为“加成序列”:

    1、X[1]=1

    2、X[m]=n

    3、X[1]<X[2]<…<X[m-1]<X[m]

    4、对于每个 k(2≤k≤m)都存在两个整数 i 和 j (1≤i,j≤k−1,i 和 j 可相等),使得X[k]=X[i]+X[j]。

    你的任务是:给定一个整数n,找出符合上述条件的长度m最小的“加成序列”。

    如果有多个满足要求的答案,只需要找出任意一个可行解。

    输入格式
    输入包含多组测试用例。

    每组测试用例占据一行,包含一个整数n。

    当输入为单行的0时,表示输入结束。

    输出格式
    对于每个测试用例,输出一个满足需求的整数序列,数字之间用空格隔开。

    每个输出占一行。

    数据范围
    1≤n≤100
    输入样例:
    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

    思路

    我们要求的是一个最短长度的序列满足他的条件,(递增,首尾限定)。那么我们根据它的数据量可以知道,这个搜索的层数是很浅,呈指数递减。所以我们迭代搜索层数。

    代码实现

    #include<cstdio>
    #include<iostream>
    #include<queue>
    #include<cmath>
    #include<algorithm>
    #include<vector>
    #include<cstring>
    using namespace std;
    const int mod=998244353;
    const int maxn=110;
    int n;
    int a[maxn];
    
    bool dfs (int u,int depth) {
       if (u==depth) return a[u-1]==n;
    
       bool vis[maxn]={false};
    
       for (int i=u-1;i>=0;i--)
         for (int j=i;j>=0;j--) {
             int ans=a[i]+a[j];
             if (ans<=n&&ans>=a[u-1]&&!vis[ans]) {
                 vis[ans]=true;
                 a[u]=ans;
                 if (dfs (u+1,depth)) return true;
             }
         }
         return false;
    }
    
    
    int main () {
        
        while (cin>>n&&n) {
           int depth=1;
           a[0]=1;
           while (!dfs (1,depth)) depth++;
           for (int i=0;i<depth;i++) cout<<a[i]<<" ";
           cout<<endl;
        }
        return 0;
    }
    
  • 相关阅读:
    监听器模式
    接口幂等性实现
    如何设计一个良好的API接口
    接口重试实现
    Spring不常用但有用的注解
    angular项目语言切换功能
    解决IOS上传竖向照片会旋转90度的问题
    微信点击链接:debugx5.qq.com提示您使用的不是x5内核
    swagger注释@API详细说明
    创建swap虚拟内存分区
  • 原文地址:https://www.cnblogs.com/hhlya/p/13355261.html
Copyright © 2011-2022 走看看