递增数列(迭代加深搜索)

it2022-05-05  108

迭代加深搜索就是限制递归的层数,然后一层层地扩大限制的层数

我们记录当前深度,以及当前应该搜出几个数

设计剪枝: 1.当当前深度乘上2^r(r是还没有选的数)比m还小 那肯定是不行的 因为最大的扩展方式就是选两个最大的数 2.这一层比上一层数小

#include<bits/stdc++.h> using namespace std; int m,step,s[1000]; bool dfs(int depth) { if(s[depth-1]==m) { cout<<step<<endl; for(int i=1;i<=step;i++) cout<<s[i]<<" "; exit(0); } if(depth>step) return false; for(register int i=depth-1;i>=1;--i) { for(register int j=depth-1;j>=i;--j) { s[depth]=s[i]+s[j]; if((s[depth]<<(step-depth))<m) break; if(s[depth]<s[depth-1]) break; dfs(depth+1); } } return false; } int main() { ios::sync_with_stdio(false); cin.tie(NULL);cout.tie(NULL); cin>>m; s[1]=1; step=1; while(!dfs(2)) ++step; }

转载于:https://www.cnblogs.com/Patrickpwq/articles/9889086.html


最新回复(0)