【POJ2248】Addition Chains

Description

Given integer n, construct an increasing sequence of positive integers such that A . 1 =. 1, A m = n, and for any k (1≤k≤m) there A K = A I + A J , minimizing sequence length (i.e. minimized m)

Solution

Due to the small size of n, so we can use iterative deepening search to solve the answer, the depth (length of the sequence) that is fixed search, search for answers, if not search for answers to the deeper depths.

So we designed search function dfs (last, now) indicates the current position being searched now, on a location value last, whether there is a solution.

Then the search is simple outlet, when now is greater than the depth defined, determines a final element of a sequence is not greater than n.

In order to improve search efficiency, we design optimized as follows:

In order to answer as soon as possible closer to n, we select reverse enumerate i, j (since the sequence is monotonically increasing), and when A i + A J stop to enumerate when ≤last.

Code

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef long long ll;
 4 int n, dep, a[110];
 5 int dfs(int last, int now) {
 6     if (now > dep) {
 7         if (a[dep] == n) return 1;
 8         return 0;
 9     }
10     for (register int i = now - 1; i >= 1; --i) {
11         for (register int j = i; j >= 1; --j) {
12             if (a[i] + a[j] > n) continue ;
13             if (a[i] + a[j] <= last) break ;
14             a[now] = a[i] + a[j];
15             if (dfs(a[now], now + 1)) return 1;
16         }
17     }
18     return 0;
19 }
20 int main() {
21     while (scanf("%d", &n) && n) {
22         a[1] = 1;
23         for (dep = 1; ; dep++) {
24             if (dfs(1, 2)) {
25                 for (register int i = 1; i <= dep; ++i)
26                     printf("%d ", a[i]);
27                 puts("");
28                 break ;
29             }
30         }
31     }
32     return 0;
33 }
AC Code

 

Guess you like

Origin www.cnblogs.com/shl-blog/p/11315559.html