概述
【题目描述】
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.
【题目链接】
Addition Chains
【算法】
枚举构造答案,迭代加深搜索。
剪枝:
1、从大到小枚举i,j
2、排除冗余(判重)
【代码】
#include <stdio.h>
#include <cstring>
using namespace std;
int n,deep;
int ans[1000],v[1000];
bool dfs(int cur) {
if(cur>deep) {
if(ans[deep]==n) return 1;
return 0;
}
for(int i=cur-1;i>=0;i--) {
for(int j=i;j>=0;j--) {
if(ans[i]+ans[j]<=n&&!v[ans[i]+ans[j]]) {
ans[cur]=ans[i]+ans[j]; v[ans[i]+ans[j]]=1;
if(dfs(cur+1)) return 1;
v[ans[i]+ans[j]]=0;
}else if(ans[i]+ans[j]<=ans[cur-1]) break;
}
}
return 0;
}
int main() {
while(~scanf("%d",&n)&&n) {
printf("1"); ans[0]=1;
if(n==1) { puts(""); continue; }
for(deep=1;!dfs(1);deep++) memset(v,0,sizeof(v));
for(int i=1;i<=deep;i++) printf(" %d",ans[i]);
puts("");
}
return 0;
}
转载于:https://www.cnblogs.com/Willendless/p/9525454.html
最后
以上就是舒心哈密瓜为你收集整理的poj 2248 Addition Chains (迭代加深搜索)的全部内容,希望文章能够帮你解决poj 2248 Addition Chains (迭代加深搜索)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复