概述
题目
An addition chain for n is an integer sequence <a0, a1,a2,…,am> 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.
solution
iddfs入门题
iddfs就是限制dfs的深度,然后加减枝,当然一定要保证有解。
#include<cstdio>
#include<algorithm>
#include<cstring>
#define fo(i,a,b) for (int (i)=(a);(i)<=(b);(i)++)
#define fd(i,b,a) for (int (i)=(b);(i)>=(a);(i)--)
using namespace std;
const int N=10005;
int a[N],n,m,dep;
int p[30];
void work(int t){
printf("%d",1);
fo(i,1,t) {
printf(" %d",a[i]);
}
printf("n");
}
bool dfs(int x){
if (x-1==dep) return a[x-1]==n;
fd(i,x-1,0) {
fd(j,i,0){
a[x]=a[i]+a[j];
if (a[x]>n) continue;
if (a[x]<=a[x-1]) break;
if (a[x]*p[dep-x]<n) return 0;
if (dfs(x+1)) return 1;
}
}
return 0;
}
int main(){
// freopen("data.in","r",stdin);
p[0]=1; fo(i,1,20) p[i]=p[i-1]*2;
while (scanf("%d",&n) && n){
a[0]=1;
m=n; dep=0;
while (m){
m/=2; dep++;
}
dep--;
for(;;){
if (dfs(1)) {
work(dep);
break;
}
dep++;
}
}
}
最后
以上就是昏睡大船为你收集整理的Addition Chains的全部内容,希望文章能够帮你解决Addition Chains所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复