列表

详情


NC51018. Addition Chains

描述

An addition chain for n is an integer sequence <a0>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>

输入描述

The input will contain one or more test cases. Each test case consists of one line containing one integer  Input is terminated by a value of zero (0) for n.

输出描述

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.

示例1

输入:

5
7
12
15
77
0

输出:

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

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++(g++ 7.5.0) 解法, 执行用时: 18ms, 内存消耗: 316K, 提交时间: 2022-10-29 16:23:41

//Author:XuHt
#include <cstring>
#include <iostream>
using namespace std;
const int N = 106;
int n, ans[N], dep;

bool dfs(int now) {
	if (now == dep) return ans[now] == n;
	bool v[N];
	memset(v, 0, sizeof(v));
	for (int i = now; i; i--)
		for (int j = i; j; j--) {
			int num = ans[i] + ans[j];
			if (num <= n && num > ans[now] && !v[num]) {
				ans[now+1] = num;
				if (dfs(now + 1)) return 1;
				else v[num] = 1;
			}
		}
	return 0;
}

int main() {
	ans[1] = 1;
	while (cin >> n && n) {
		dep = 1;
		while (!dfs(1)) ++dep;
		for (int i = 1; i <= dep; i++) cout << ans[i] << " ";
		cout << endl;
	}
	return 0;
}

C++(clang++11) 解法, 执行用时: 10ms, 内存消耗: 296K, 提交时间: 2022-04-20 22:35:32

#include<bits/stdc++.h>
using namespace std;
const int N=205;
int n,dm,d[N];
bool vis[N],fl;
inline void dfs(int x,int lst){
	if(x>dm){
		if(d[dm]==n)fl=true;
		return;
	}
	for(int i=lst;i<x;i++){
		for(int j=1;j<=i;j++){
			d[x]=d[i]+d[j];
			dfs(x+1,i+1);
			if(fl)return;
			d[x]=0;
		}
	}
}
int main(){
	while(~scanf("%d",&n)){
		if(n==0) break;
		dm=1;
		memset(vis,0,sizeof(vis));
		fl=false;
		d[1]=1;
		for(;!fl;dm++)dfs(2,1);
		for(int i=1;i<dm;i++) printf("%d ",d[i]);
		puts("");
	}
	return 0;
}

上一题