容易想到建图,即将 和 连边, 和 连边。特别地,当 时只需要建一条边。
然后这个图就是一条链带个自环之类的东西了,拓扑就完了。
#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;
}