UVA 529 - Addition Chains,迭代加深搜索+剪枝

Description

An addition chain for n is an integer sequence UVA 529 - Addition Chains,迭代加深搜索+剪枝 with the following four properties:

  • a0 = 1
  • am = n
  • a0<a1<a2<...<am-1<am
  • For each k ( UVA 529 - Addition Chains,迭代加深搜索+剪枝) there exist two (not neccessarily different) integers i and j ( UVA 529 - Addition Chains,迭代加深搜索+剪枝) 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 Specification

The input file will contain one or more test cases. Each test case consists of one line containing one integer n ( UVA 529 - Addition Chains,迭代加深搜索+剪枝). Input is terminated by a value of zero (0) for n.

Output Specification

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 大致题意:
  给你个n,找从 0 到 n 的最短序列,序列满足 每一个 a[k] 都存在a[i]+a[j]=a[k],如果有很多,找到一个就够了。
解题思路:
  用迭代加深搜索实现,需要注意很多地方剪枝。
 #include <iostream>
#include <cstring>
using namespace std;
int n,ans[];
bool finish;
void dfs(int x,int deep){
if(finish) return ;
if(x==deep) { if(ans[x]==n)finish=; return; }
for(int i=;i<=x;i++){
for(int j=i;j<=x;j++) if(ans[i]+ans[j]>ans[x]&&ans[i]+ans[j]<=n){//剪枝
int sum=ans[i]+ans[j];
for(int k=x+;k<=deep;k++) sum<<=;//sum *= 2;当前为x; sum存于x+1;
if(sum<n) continue;//如果接下来一直是最大策略还是不能达到n,剪枝
ans[x+]=ans[i]+ans[j];
dfs(x+,deep);
if(finish) return ;
}
}
}
int main(){
while(scanf("%d",&n),n){
memset(ans,,sizeof(ans));
ans[finish=]=;
int tmp=n,deep=; while(tmp>>=) deep++;//求出最大深度;
while(!finish) dfs(,deep++);
cout<<ans[];
for(int i=;i<deep;i++) cout<<" "<<ans[i];
cout<<endl;
}return ;
}
上一篇:.NET Core WEB API中接口参数的模型绑定的理解


下一篇:asp.net core 多端口监听&日志服务