170 加成序列 dfs 剪枝

// 170 加成序列.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
/*
https://www.acwing.com/problem/content/172/
满足如下条件的序列 X(序列中元素被标号为 1、2、3…m)被称为“加成序列”:

X[1]=1
X[m]=n
X[1]<X[2]<…<X[m−1]<X[m]
对于每个 k(2≤k≤m)都存在两个整数 i 和 j (1≤i,j≤k−1,i 和 j 可相等),使得 X[k]=X[i]+X[j]。
你的任务是:给定一个整数 n,找出符合上述条件的长度 m 最小的“加成序列”。

如果有多个满足要求的答案,只需要找出任意一个可行解。

输入格式
输入包含多组测试用例。

每组测试用例占据一行,包含一个整数 n。

当输入为单行的 0 时,表示输入结束。

输出格式
对于每个测试用例,输出一个满足需求的整数序列,数字之间用空格隔开。

每个输出占一行。

数据范围
1≤n≤100
输入样例:
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
*/


#include <iostream>
#include <cstring>


using namespace std;

const int N = 150;
int arr[N];
int idx;
int n;
int ans;
int ansArr[N];
int hah[N];

void dfs(int x) {
	if (arr[x] == n) {
		if (ans > (x + 1)) {
			ans = x + 1;
			memcpy(ansArr, arr, sizeof ansArr);
		}
		return;
	}
	if (arr[x] > n) return;
	if (x >= ans) return;


	//查找比arr[x] 大的后继
	int v = arr[x]; int flag = 0;
	int back[N];
	memcpy(back, hah, sizeof hah);

	for (int i = x; i >= 0; i--) {
		if (flag == 1) break;
		for (int j = i; j >= 0; j--) {
			if (arr[i] + arr[j] <= v){flag = 1; break;}
			if (hah[arr[i] + arr[j]] != 0) continue;
			arr[x + 1] = arr[i] + arr[j];
			hah[arr[i] + arr[j]] += 1;
			dfs(x + 1);
		}
	}

	memcpy(hah, back, sizeof hah);
	return ;
}



void solve() {
	dfs(0);

	for (int i = 0; i < ans ;i++) {
		cout << ansArr[i] << " ";
	}
	cout << endl;
}


int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	while (cin >> n) {
		if (n == 0) break;
		idx = 0; ans = 9999999;
		arr[idx++] = 1;
		if (n == 1) { cout << 1 << endl; continue; }
		memset(hah, 0, sizeof hah);
		solve();
	}
	
	return 0;
}

posted on 2024-07-18 15:26  itdef  阅读(4)  评论(0编辑  收藏  举报

导航