加成序列(迭代加深)

在这里插入图片描述

思路:满足题设的4个条件,第一个数一定是1,最后的数一定是n,数列单调递增,后面的数是由前面某2个数相加得来的。其中一些条件可以作为可行性剪枝,搜索时,我们去从小到大逐层搜m,因为条件4的的存在,我们会发现如1 2 3 5这种答案和1 2 4 5都是可行的,5可由2+3或者1+4得来那么我们就需要标记一下防止重复搜索。

#pragma GCC optimize(2)
#include<bits/stdc++.h>
 
using namespace std;
typedef long long ll;
#define SIS std::ios::sync_with_stdio(false)
#define space putchar(' ')
#define enter putchar('\n')
#define lson root<<1
#define rson root<<1|1
typedef pair<int,int> PII;
typedef pair<int,PII> PIII;
const int mod=1e9+7;
const int N=2e5+5;
const int inf=0x7f7f7f7f;

int gcd(int a,int b)
{
    
    
    return b==0?a:gcd(b,a%b);
}
 
ll lcm(ll a,ll b)
{
    
    
    return a*(b/gcd(a,b));
}
 
template <class T>
void read(T &x)
{
    
    
    char c;
    bool op = 0;
    while(c = getchar(), c < '0' || c > '9')
        if(c == '-')
            op = 1;
    x = c - '0';
    while(c = getchar(), c >= '0' && c <= '9')
        x = x * 10 + c - '0';
    if(op)
        x = -x;
}
template <class T>
void write(T x)
{
    
    
    if(x < 0)
        x = -x, putchar('-');
    if(x >= 10)
         write(x / 10);
    putchar('0' + x % 10);
}
ll qsm(int a,int b,int p)
{
    
    
    ll res=1%p;
    while(b)
    {
    
    
        if(b&1)
            res=res*a%p;
        a=1ll*a*a%p;
        b>>=1;
    }
    return res;
}

int path[N];
int n;

bool dfs(int u,int dep)
{
    
    
    if(u>dep)return false;
    if(path[u-1]==n)return true;
    int vis[110]={
    
    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||s<=path[u-1]||vis[s])continue;
            vis[s]=1;
            path[u]=s;
            if(dfs(u+1,dep))return true;
        }
    }
    return false;

}
int main()
{
    
    

   
   path[0]=1;
   while(cin>>n,n)
   {
    
    
      // memset(vis,0,sizeof vis);
       int dep=1;
       while(!dfs(1,dep))dep++;
       for(int i=0;i<dep;i++)cout<<path[i]<<' ';
       cout<<endl;
   } 
       

   
      
   return 0;

}


猜你喜欢

转载自blog.csdn.net/qq_43619680/article/details/112502447