[POJ 2248]Addition Chains

Description

An addition chain for n is an integer sequence with the following four properties:

  • a0 = 1
  • am = n
  • a0 < a1 < a2 < ... < am-1 < am
  • For each k (1<=k<=m) there exist two (not necessarily different) integers i and j (0<=i, j<=k-1) with ak=ai+aj


You are given an integer n. Your job is to construct an addition chain for n with minimal length. If there is more than one such sequence, any one is acceptable.
For example, <1,2,3,5> and <1,2,4,5> are both valid solutions when you are asked for an addition chain for 5.

Input

The input will contain one or more test cases. Each test case consists of one line containing one integer n (1<=n<=100). Input is terminated by a value of zero (0) for n.

Output

For each test case, print one line containing the required integer sequence. Separate the numbers by one blank.
Hint: The problem is a little time-critical, so use proper break conditions where necessary to reduce the search space.

Sample Input

5
7
12
15
77
0

Sample Output

1 2 4 5
1 2 4 6 7
1 2 4 8 12
1 2 4 5 10 15
1 2 4 8 9 17 34 68 77

题解

考虑迭代加深的$dfs$
我们一开始可以算出最少需要多少个,就是答案的下界
这个怎么算呢?从$1$开始不断乘$2$,看什么时候比$n$大,就是下界
然后将答案往上加,用$dfs$判断是否可行
这样我们可以进行减枝了
如果当前的答案是$ans$,当前搜索的位置是$x$
如果$a[x]*2^{ans-x}$还比$n$小,就可以$return$了
这样就可以搜过去了

 

 1 #include<map>
 2 #include<set>
 3 #include<cmath>
 4 #include<ctime>
 5 #include<queue>
 6 #include<stack>
 7 #include<vector>
 8 #include<cstdio>
 9 #include<string>
10 #include<cstdlib>
11 #include<cstring>
12 #include<iostream>
13 #include<algorithm>
14 #define LL long long
15 #define RE register
16 #define IL inline
17 using namespace std;
18 
19 int n,depth;
20 int ans[105];
21 
22 bool Dfs(int cen,int dep)
23 {
24     if (cen==dep)
25     {
26         if (ans[cen]==n) return true;
27         return false;
28     }
29     for (int i=1;i<=cen;i++) for (RE int j=1;j<=i;j++)
30     {
31         if (((ans[i]+ans[j])<<(dep-cen-1))<n) continue;
32         ans[cen+1]=ans[i]+ans[j];
33         if (Dfs(cen+1,dep)) return true;
34     }
35     return false;
36 }
37 
38 int main()
39 {
40     ans[1]=1;
41     while (scanf("%d",&n)&&n)
42     {
43         depth=log2(n)+1;
44         while (true)
45         {
46             if (Dfs(1,depth)) break;
47             depth++;
48         }
49         for (RE int i=1;i<=depth;i++) printf("%d ",ans[i]);
50         printf("\n");
51     }
52     return 0;
53 }

 

转载于:https://www.cnblogs.com/NaVi-Awson/p/7353863.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值