【解题报告】 加成序列
解题思路:
dfs+剪枝+迭代加深
这道题我们可以看出任何序列的长度都在10左右,所以这道题我们可以很好地看出是用迭代加深来解决问题
所以我们为了让序列中的数尽快逼近n,在枚举i和j时,可以从大到小枚举
然后我们还需要一个判重,因为不让两个数加起来等于第三个数多次
AC代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
| #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; const int maxn=110; int n; int path[maxn]; bool dfs(int u,int depth) { if(u==depth) return path[u-1]==n; bool st[maxn]={false}; for(int i=u-1;i>=0;i--) { for(int j=i;j>=0;j--) { int s=path[i]+path[j]; if(s>=path[u-1]&&s<=n&&!st[s]) { st[s]=true; path[u]=s; if(dfs(u+1,depth)) return true; } } } return false; } int main() { while(cin>>n&&n) { int depth=1; path[0]=1; while(!dfs(1,depth)) depth++; for(int i=0;i<depth;i++) cout<<path[i]<<" "; cout<<endl; } return 0; }
|