跳到正文

题解

题解:AT_utpc2021_b Swap and Maximize

原文
文章信息与版本

文章信息

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

版本

  1. v1当前

我们考虑将 AA 与 BB 混合后排序得到 C1,2,⋯ ,2NC_{1,2,\cdots,2N}。将其分为两个等长序列 A′A' 与 B′B',考查这种情况下能达到的极值。

我们不妨 AN′=C2NA'_N=C_{2N}。我们假设 BN′B'_N 为 B′B' 序列的最大值且 BN′≠C2N−1B'_N\not=C_{2N-1},那么可以不妨 AN−1′=C2N−1A'_{N-1}=C_{2N-1} 成立。这种情况下,BN′B'_N 与 AN−1′A'_{N-1} 造成的对外总贡献为 ∑i=1N−2min⁡{Ai′,BN′}+BN′+∑i=1N−1Bi′\sum_{i=1}^{N-2}\min\{A'_i,B'_N\}+B'_N+\sum_{i=1}^{N-1}B'_i,第三个部分是因为 ∀1≤i<N\forall 1\le i\lt N 均有 Bi′≤AN−1′B'_i\le A'_{N-1}。我们注意到 ∀1≤i<N\forall 1\le i\lt N 同样均有 Bi′≤BN′B'_i\le B'_N,于是如果我们交换 BN′B'_N 与 AN−1′A'_{N-1},可以得到总贡献为 ∑i=1N−2min⁡{Ai′,AN−1′}+AN−1′+∑i=1N−1Bi′\sum_{i=1}^{N-2}\min\{A'_i,A'_{N-1}\}+A'_{N-1}+\sum_{i=1}^{N-1}B'_i,其中序列值的含义依然沿用交换前。我们注意到贡献没有变小,于是一定存在方案使得 BN′=C2N−1B'_N=C_{2N-1}。

我们注意到此时这两项造成的总贡献是固定的,于是我们可以删掉它们继续如法炮制。最终我们得到:总贡献达到最大时,存在一种方案使 ∀1≤i≤N\forall 1\le i\le N 有 C2i−1C_{2i-1} 与 C2iC_{2i} 分属不同的序列。注意到此时总贡献是唯一的,所以只要 ∀1≤i≤N\forall 1\le i\le N 有 C2i−1C_{2i-1} 与 C2iC_{2i} 分属不同的序列,总贡献即达到最大。

回到原题,我们给出如下说法:即使只允许交换 AiA_i 和 BiB_i,我们依然可以达到最大的总贡献。我们考虑只能交换 AiA_i 和 BiB_i 相当于宣告这两个点分属不同的序列,而总贡献最大的条件是 ∀1≤i≤N\forall 1\le i\le N 有 C2i−1C_{2i-1} 与 C2iC_{2i} 分属不同的序列。我们将这 2N2N 条边连出来,会发现每个点的度数恰为 22。换而言之,全图由若干个环构成。这样的图必然是二分图,于是一定存在一种黑白染色方案。依照这个方案决定是否交换 AiA_i 和 BiB_i 即可。

代码非常好写。

C++
#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;
}
原文