Iterative deepening --------- addition sequence

Sequence satisfies the condition X (sequence elements being numbered 1,2,3 ... m) is referred to as "Addition Sequence":
. 1, X-[. 1]. 1 =
2, X-[m] = n-
. 3, X-[ . 1] <X-[2] <... <X-[-m. 1] <X-[m]
. 4, for each kk (2≤k≤m2≤k≤m) there are two integers ii and jj (1≤i , j≤k-11≤i, j≤k-1 , ii and jj may be equal), such that X [k] = X [i ] + X [j].
Your task is: given an integer n, m meet the above conditions to find the length of the smallest "Addition Sequence."
If there are multiple answers to meet the requirements, you only need to find a feasible solution to any.
Input format
input comprises a plurality of test cases.
Each test line, that contains an integer n.
When the input is a single row 0, indicating the end of input.
Output Format
For each test case, the output of a sequence of integers to meet the demand, separated by spaces between numbers.
Each output per line.
Data range
1≤n≤1001≤n≤100
Input Sample:
. 5
. 7
12 is
15
77
0

Output Sample:
. 1 2. 5. 4
. 1 2. 4. 6. 7
. 1 12 is 2. 8. 4
. 1 10 15 2. 5. 4
. 1. 17 34 is 2 68. 4. 9 77. 8

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace  std;
const int N = 110;
int n;
int path[N];
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 ++)    cout << path[i] << ' ';
      cout << endl;
 }
  return 0;
}
发布了59 篇原创文章 · 获赞 48 · 访问量 4656

Guess you like

Origin blog.csdn.net/qq_45772483/article/details/104637710