题解:AT_utpc2021_b Swap and Maximize
我们考虑将
我们不妨
我们注意到此时这两项造成的总贡献是固定的,于是我们可以删掉它们继续如法炮制。最终我们得到:总贡献达到最大时,存在一种方案使
回到原题,我们给出如下说法:即使只允许交换
代码非常好写。
#include <bits/stdc++.h>
using namespace std;
constexpr int N = 2e5 + 9, M = N << 1;
int T, n, m, tot, a[M], id[M], col[M], hd[M];
struct {
int to, nxt;
} es[M << 1];
void add(int u, int v) {
es[tot] = {v, hd[u]}, hd[u] = tot++;
es[tot] = {u, hd[v]}, hd[v] = tot++;
}
void dfs(int x) {
for (int i = hd[x], y; ~i; i = es[i].nxt)
if (!~col[y = es[i].to]) col[y] = !col[x], dfs(y);
}
signed main() {
cin.tie(nullptr)->sync_with_stdio(false);
for (cin >> T; T; --T) {
cin >> n, iota(id, id + (m = n << 1), 0);
for (int i = 0; i < m; ++i) cin >> a[i];
sort(id, id + m, [](int x, int y) { return a[x] < a[y]; });
memset(col, -1, m * sizeof(int));
memset(hd, -1, m * sizeof(int));
for (int i = 0; i < n; ++i) add(id[i << 1], id[i << 1 | 1]);
for (int i = 0; i < n; ++i) add(i, i + n);
for (int i = 0; i < n; ++i)
if (!~col[i])
col[i] = 0, dfs(i);
else if (col[i])
swap(a[i], a[i + n]);
for (int i = 0; i < n; ++i) cout << a[i] << ' ';
cout << '\n';
for (int i = 0; i < n; ++i) cout << a[i + n] << ' ';
cout << '\n';
}
return cout << flush, 0;
}