本题解为确定性算法,由 ChatGPT 5.5 Thinking 编写,本人进行了一些格式化。
关键观察
设每组需要超过 头 Jersey 的奶牛。
如果存在一组可行划分,那么一定存在两个获胜组,它们一共包含 个城市,且这两个组的 Jersey 奶牛数都严格大于 。
我们把所有城市按 从大到小排序,取前 个城市,记为集合 。
结论是:
如果原问题有解,那么这前 个城市也一定能被分成两个大小为 的组,并且两组的 Jersey 奶牛数都严格大于 。
所以问题变成:
在前 个城市里,找一个大小为 的子集,使它的权值和为 ,满足 。其中 是前 个城市的权值总和。
这样这个子集作为第一组,剩下的前 个城市作为第二组,剩余 个城市作为第三组即可。
正确性证明
假设原问题有解,存在两个满足条件的组 ,每组 个城市,且 。
令 ,则 是某 个城市的集合。
把 中城市权值从大到小排序为 ,把所有城市中权值最大的前 个城市排序为 。由于 是全体城市中最大的 个,所以对任意 都有 。
现在保留 中每个位置原来属于 还是 的标签。
如果 属于 ,就把 分到新组 ;如果 属于 ,就把 分到新组 。
因为原来 都有 个城市,所以新组 也都恰好有 个城市。并且 ,,所以前 个城市一定可以分成两个满足条件的组。
接下来,只要在前 个城市中找到一个大小为 的子集,设其权值和为 。它的补集也有 个城市,权值和为 。
要求两组都获胜,即 且 ,也就是 ,由于题目保证有解,根据上面的证明,这样的子集一定存在。
DP 做法
在前 个城市中做 0/1 背包。
定义 表示能否从已经考虑的城市中选出 个城市,使权值和为 。
为了方便回溯,用前缀 DP, 表示只考虑前 个候选城市,是否能选出 个城市,权值和为 。
最后找一个 ,满足 并且 ,然后回溯得到第一组。
复杂度
前 ,每组最多 ,单组权值和最多 。
时间复杂度 ,使用 bitset 后非常快。
空间复杂度约为 ,按 bit 存储,约 55MB。
C++17 代码
#include <bits/stdc++.h>
using namespace std;
const int MAXK = 60;
const int MAXN = 120;
const int MAXS = 60000;
bitset<MAXS + 1> pre[MAXN + 1][MAXK + 1];
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int k;
cin >> k;
int n = 3 * k;
vector<pair<int, int>> a(n);
for (int i = 0; i < n; i++) {
int w;
cin >> w;
a[i] = {w, i + 1};
}
sort(a.begin(), a.end(), [](auto &x, auto &y) {
if (x.first != y.first) return x.first > y.first;
return x.second < y.second;
});
int m = 2 * k;
int maxSum = 1000 * k;
int T = 500 * k;
int totalTop = 0;
for (int i = 0; i < m; i++) {
totalTop += a[i].first;
}
pre[0][0][0] = 1;
for (int i = 1; i <= m; i++) {
int w = a[i - 1].first;
for (int c = 0; c <= k; c++) {
pre[i][c] = pre[i - 1][c];
}
for (int c = 1; c <= k; c++) {
pre[i][c] |= (pre[i - 1][c - 1] << w);
}
}
int L = T + 1;
int R = totalTop - T - 1;
R = min(R, maxSum);
int target = -1;
for (int s = L; s <= R; s++) {
if (pre[m][k][s]) {
target = s;
break;
}
}
// 题目保证有解,所以正常情况下一定能找到
if (target == -1) {
return 0;
}
vector<int> group1, group2, group3;
vector<int> used(m, 0);
int c = k;
int s = target;
for (int i = m; i >= 1; i--) {
int w = a[i - 1].first;
if (pre[i - 1][c][s]) {
continue;
} else {
used[i - 1] = 1;
group1.push_back(a[i - 1].second);
s -= w;
c--;
}
}
for (int i = 0; i < m; i++) {
if (!used[i]) {
group2.push_back(a[i].second);
}
}
for (int i = m; i < n; i++) {
group3.push_back(a[i].second);
}
for (int x : group1) {
cout << x << '\n';
}
for (int x : group2) {
cout << x << '\n';
}
for (int x : group3) {
cout << x << '\n';
}
return 0;
}这个算法是确定性的,且由于题目保证有解,最终一定能找到合法划分。