[POJ 2248]Addition Chains

时间:2023-02-02 20:01:39

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$了
这样就可以搜过去了

 #include<map>
#include<set>
#include<cmath>
#include<ctime>
#include<queue>
#include<stack>
#include<vector>
#include<cstdio>
#include<string>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LL long long
#define RE register
#define IL inline
using namespace std; int n,depth;
int ans[]; bool Dfs(int cen,int dep)
{
if (cen==dep)
{
if (ans[cen]==n) return true;
return false;
}
for (int i=;i<=cen;i++) for (RE int j=;j<=i;j++)
{
if (((ans[i]+ans[j])<<(dep-cen-))<n) continue;
ans[cen+]=ans[i]+ans[j];
if (Dfs(cen+,dep)) return true;
}
return false;
} int main()
{
ans[]=;
while (scanf("%d",&n)&&n)
{
depth=log2(n)+;
while (true)
{
if (Dfs(,depth)) break;
depth++;
}
for (RE int i=;i<=depth;i++) printf("%d ",ans[i]);
printf("\n");
}
return ;
}