[POJ 2248]Addition Chains
Addition Chains
Time Limit: 1000MS | Memory Limit: 65536K | |||
Total Submissions: 5263 | Accepted: 2829 | Special Judge |
Description
An addition chain for n is an integer sequence <a0, a1,a2,...,am="">with the following four properties:
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.
- 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.
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
题目大意
请构造一个尽量短的序列 A,长度为 len,一开始会给你一个正整数 n,
满足以下条件:
A[1]=1
A[len]=n
A[i]>A[i-1] (len>=i>=2)
A[x]=A[i]+A[j] (1<=i,j<x)
题解:
考虑迭代加深的dfs
我们一开始可以算出最少需要多少个,就是答案的下界
这个怎么算呢?从1开始不断乘2,看什么时候比n大,就是下界
然后将答案往上加,用dfs判断是否可行
这样我们可以进行减枝了
如果当前的答案是ans,当前搜索的位置是x
如果 a[x]*(2^(ans-x))还比n小,就可以 return 了
这样就可以搜过去了
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> using namespace std; int n,ans[101],depth; bool flag; void dfs(int cur) { if(flag)return; if(depth==cur) { if(ans[cur]==n)flag=true; return; } int i,j,k; for(i=0;i<=cur;i++) for(j=i;j<=cur;j++) if(ans[i]+ans[j]>ans[cur]&&ans[i]+ans[j]<=n) { ans[cur+1]=ans[i]+ans[j]; int x=ans[cur+1]; for(k=cur+1;k<=depth;k++)x*=2; if(x<n)continue; dfs(cur+1); if(flag)return; } } int main() { int i,j; while(scanf("%d",&n)!=EOF) { if(!n)break; if(n==1){printf("1\n");continue;} memset(ans,0,sizeof(ans)); flag=false; ans[0]=1; depth=0; int x=1; while(1) { x*=2; depth++; if(x>=n)break; } while(1) { dfs(0); if(flag)break; depth++; } for(i=0;i<=depth;i++) printf("%d ",ans[i]); printf("\n"); } return 0; }