跳到正文

题解

题解:P12026 [USACO25OPEN] Compatible Pairs S

donaldqian约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年4月16日
收录
2025年12月12日
更新
2026年11月22日
篇幅
约 3 分钟
获赞
6
题目
P12026

版本

  1. v1当前

容易想到建图,即将 did_i 和 A−diA-d_i 连边,did_i 和 B−diB-d_i 连边。特别地,当 A=BA=B 时只需要建一条边。

然后我们会发现这个图不可能存在长度 ≥3\ge 3 的环,证明如下:

然后这个图就是一条链带个自环之类的东西了,拓扑就完了。

C++
#include <bits/stdc++.h>
using namespace std;

const int maxn = 200010;
int head[maxn], to[maxn << 1], nxt[maxn << 1], cnte, in[maxn];
void addedge (int u, int v) { in[v]++, to[++cnte] = v, nxt[cnte] = head[u], head[u] = cnte; }

bool vis[maxn];
unordered_map <int, int> mp;
long long ans; queue <int> que;
int n, a, b, t, d[maxn], v[maxn];

signed main () {
	scanf("%d%d%d", &n, &a, &b);
	for (int i = 1; i <= n; i++) scanf("%d%d", &v[i], &d[i]), mp[d[i]] = i;
	for (int i = 1; i <= n; i++) {
		if (mp.find (a - d[i]) != mp.end ()) addedge (i, mp[a - d[i]]);
		if (a != b && mp.find (b - d[i]) != mp.end ()) addedge (i, mp[b - d[i]]);
	}
	for (int i = 1; i <= n; i++) if (in[i] == 1) que.push (i);
	while (!que.empty ()) {
		int u = que.front (); que.pop ();
		for (int i = head[u]; i; i = nxt[i]) {
			if (vis[to[i]]) continue;
			if (to[i] == u) ans += v[u] / 2, v[u] &= 1;
			else t = min (v[u], v[to[i]]), ans += t, v[u] -= t, v[to[i]] -= t;
			if (--in[to[i]] == 1) que.push (to[i]);
		}
		vis[u] = 1;
	}
	printf("%lld", ans);
	return 0;
}
原文
存档评论2 条抓取于