题解:P1675 [USACO05FEB] Jersey Politics G
CuteMurasame · · 题解
本题解为确定性算法,由 ChatGPT 5.5 Thinking 编写,本人进行了一些格式化。
关键观察
设每组需要超过
如果存在一组可行划分,那么一定存在两个获胜组,它们一共包含
我们把所有城市按
结论是:
如果原问题有解,那么这前
2k 个城市也一定能被分成两个大小为k 的组,并且两组的 Jersey 奶牛数都严格大于T 。
所以问题变成:
在前
这样这个子集作为第一组,剩下的前
正确性证明
假设原问题有解,存在两个满足条件的组
令
把
现在保留
如果
因为原来
接下来,只要在前
要求两组都获胜,即
DP 做法
在前
定义
为了方便回溯,用前缀 DP,
最后找一个
复杂度
前
时间复杂度
空间复杂度约为
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;
}
这个算法是确定性的,且由于题目保证有解,最终一定能找到合法划分。