题目链接:Acwing_170加成序列
搜索框架: 依次搜索序列中的每个位置k,枚举i和 j 作为分支,把X[i]和 X[j]的和填写到x[k]上,然后递归填写下一个位置
加入以下剪枝:
- 优化搜索顺序
为了让序列中的数尽快逼近n,在枚举i 和j 时从大到小枚举。 - 排除等效冗余
对于不同的i和 j,X[i]+X[]可能是相等的。我们可以在枚举时用一个bool数组对X[i]+X[j]进行判重,避免重复搜索某一个和。
经过观察分析可以发现,m 的值(序列长度)不会太大(≤10),而每次枚举两个数的和,分支很多。所以我们采用迭代加深的搜索方式,从1开始限制搜索深度,若搜索失败就增加深度限制重新搜索,直到找到一组解时即可输出答案。
AC代码:
//迭代加深
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int N = 101;
int n;
int path[N];
//u表示当前层数,depth表示最大层数
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 || s <= path[u - 1] || st[s]) continue;
st[s] = true;
path[u] = s;
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++) {
printf("%d ", path[i]);
}
printf("\n");
}
system("pause");
return 0;
}