跳到正文

题解

【题解】P12026 [USACO25OPEN] Compatible Pairs S

qW__Wp约 4 分钟
原文
文章信息与版本

文章信息

发布
2025年4月9日
收录
2026年7月24日
更新
2026年11月14日
篇幅
约 4 分钟
获赞
8
题目
P12026

版本

  1. v2当前
  2. v1

Update 2026/8/7:重写题解。

建一个无向图。对于每个 x=dix = d_i:

  • 若 x≤Ax \le A,将其向 A−xA - x 连边;
  • 若 A≠B,x≤BA \not = B, x \le B,将其向 B−xB - x 连边。

考察一个连通块的性质:

  1. 每个点的度数 ≤2\le 2,形成链状。

  2. 不存在长度 ≥3\ge 3 的环。

证明

当 A=BA = B 时易证。

若 A≠BA \not = B:

考虑连边本质:称变换 AA 为使 xx 变为 A−xA - x,变换 BB 为使 xx 变为 B−xB - x。变换成立的前提是变换前后均为非负数。

有意义的变换是 ABAB 交替的,不妨设第一次为变换 AA,则 x⟶AA−x⟶BB−(A−x)=x+(B−A)⟶A⋯x \overset{A}\longrightarrow A-x \overset{B}\longrightarrow B - (A - x) = x + (B - A) \overset{A}\longrightarrow \cdots。

首先要注意到两个东西:

  • 两次变换由 x→x+(B−A)x \to x + (B - A),相当于在数轴上移动了 (B−A)(B - A) 的距离(注意我们设第一次为变换 AA)。
  • 一次变换 AA 相当于得到 xx 在数轴上关于 A/2A/2 的对称点,原因是 x+A−x2=A/2\dfrac{x + A - x}{2} = A/2。

假设从 xx 出发能够回到 xx,即 x⟶AA−x⟶Bx+(B−A)⟶A⋯⟶xx \overset{A}\longrightarrow A-x \overset{B}\longrightarrow x + (B - A) \overset{A}\longrightarrow \cdots \longrightarrow x。

  • 若共进行偶数次变换,则移动了 k(B−A)k(B - A) 的距离,其中 k>0,(B−A)>0k > 0, (B - A) > 0,故 k(B−A)>0k(B - A) > 0,不可能回到 xx;

  • 若共进行奇数次变换,则最后一次进行了变换 AA,即关于 A/2A/2 对称,要想回到 xx 必然有对称中心 A/2=xA/2 = x,即形成自环。

证毕。

  1. 自环仅可能出现在链的两端。由性质 1 可得。

  2. 存在至多 11 个自环。否则 A/2=B/2A/2 = B/2 得 A=BA = B,矛盾。

结论:这是一条链,至多有一个位于链的端点的自环。

由此可知最优策略:先忽略自环,从链的两端向中间流动(相当于拓扑排序),最后处理自环。

C++
#include <bits/stdc++.h>
#define endl '\n'

using namespace std;

typedef long long ll;
const int N = 2e5 + 5;

int x[N], d[N], deg[N];
unordered_map<int, int> f;
bool self[N];
vector<int> G[N];

signed main() {
	//freopen("", "r", stdin);
	//freopen("", "w", stdout);
	ios::sync_with_stdio(0), cin.tie(0);
	int n, A, B; cin >> n >> A >> B;
	f.reserve(n);
	for (int i = 1; i <= n; i ++) {
		cin >> x[i] >> d[i];
		f[d[i]] = i;
	}
	for (int i = 1; i <= n; i ++) {
		if (f[A - d[i]] && A - d[i] != d[i]) {
			G[i].push_back(f[A - d[i]]);
			deg[f[A - d[i]]] ++;
		}
		if (A != B && f[B - d[i]] && B - d[i] != d[i]) {
			G[i].push_back(f[B - d[i]]);
			deg[f[B - d[i]]] ++;
		}
		self[i] = A - d[i] == d[i] || B - d[i] == d[i];
	}
	// 先处理链的情况,自环在最后单独考虑
	queue<int> q;
	for (int i = 1; i <= n; i ++) {
		if (deg[i] == 1) q.push(i);
	}
	ll res = 0;
	while (!q.empty()) {
		int u = q.front(); q.pop();
		for (auto& v : G[u]) {
			int get = min(x[u], x[v]);
			x[u] -= get, x[v] -= get, res += get;
			deg[v] --;
			if (deg[v] == 1) q.push(v);
		}
	}
	for (int i = 1; i <= n; i ++) {
		if (self[i]) res += x[i] / 2;
	}
	cout << res;
	return 0;
}
原文
存档评论2 条抓取于