跳到正文

题解

题解:子集の子集

__Groyhj__QwQ约 2 分钟
原文

这是 2025年9月16日 存档的第 2 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟

版本

  1. v5当前
  2. v4
  3. v3
  4. v2
更早的 1 个版本
  1. v1

子集の子集题解

CF 链接。

1. 题意概括

2. 思路分析

3. AC 代码

AC 记录。

C++
#include <bits/stdc++.h>
#define int long long
using namespace std;
int a[502];
bool dp[502][502][502];
vector<int> ans;
signed main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int n, k;
	cin >> n >> k;
	for (int i = 1; i <= n; i++) {
		cin >> a[i];
	}
	dp[0][0][0] = 1;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j <= k; j++) {
			for (int l = 0; l <= k; l++) {
				dp[i + 1][j][l] |= dp[i][j][l];
				if (j + a[i + 1] <= k) {
					dp[i + 1][j + a[i + 1]][l] |= dp[i][j][l];
				} 
				if (l + a[i + 1] <= k) {
					dp[i + 1][j][l + a[i + 1]] |= dp[i][j][l];
				}
			}
		}
	}
	for (int i = 0; i <= k; i++) {
		if (dp[n][i][k - i]) {
			ans.push_back(i);
		}
	}
	cout << ans.size() << endl;
	for (auto i : ans) {
		cout << i << " ";
	}
	return 0;
}