0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-11-23 20:48:48 +00:00

P3386 【模板】二分图最大匹配

https://www.luogu.com.cn/record/103040235
This commit is contained in:
Baoshuo Ren 2023-02-26 08:20:56 +08:00
parent 5777c81c18
commit 51e252392e
Signed by: baoshuo
GPG Key ID: 00CB9680AB29F51A

View File

@ -1,5 +1,6 @@
#include <iostream> #include <iostream>
#include <algorithm> #include <algorithm>
#include <iterator>
#include <queue> #include <queue>
using std::cin; using std::cin;
@ -10,19 +11,19 @@ const int N = 505,
M = 5e4 + 5; M = 5e4 + 5;
const int INF = 0x3f3f3f3f; const int INF = 0x3f3f3f3f;
int n, m, e, s, t, flow, ans; int n, m, e, s, t;
int idx, head[N << 1], ver[M << 2], edge[M << 2], next[M << 2]; int idx, head[N << 1], ver[M << 2], edge[M << 2], next[M << 2];
int d[N << 1], cur[N << 1]; int d[N << 1], cur[N << 1];
void add(int u, int v, int w) { void add(int u, int v, int w) {
next[idx] = head[u];
ver[idx] = v; ver[idx] = v;
edge[idx] = w; edge[idx] = w;
next[idx] = head[u];
head[u] = idx++; head[u] = idx++;
} }
bool bfs() { bool bfs() {
std::fill_n(d, N << 1, 0); std::fill(std::begin(d), std::end(d), 0);
std::queue<int> q; std::queue<int> q;
@ -38,7 +39,7 @@ bool bfs() {
int v = ver[i], int v = ver[i],
w = edge[i]; w = edge[i];
if (w && !d[v]) { if (!d[v] && w) {
d[v] = d[u] + 1; d[v] = d[u] + 1;
cur[v] = head[v]; cur[v] = head[v];
if (v == t) return true; if (v == t) return true;
@ -54,20 +55,21 @@ int dinic(int u, int limit) {
if (u == t) return limit; if (u == t) return limit;
int flow = 0; int flow = 0;
for (int i = cur[u]; ~i && flow < limit; i = next[i]) { for (int i = cur[u]; ~i && flow < limit; i = next[i]) {
cur[u] = i; cur[u] = i;
int v = ver[i], int v = ver[i],
w = edge[i]; w = edge[i];
if (w && d[v] == d[u] + 1) { if (d[v] == d[u] + 1 && w) {
int k = dinic(v, std::min(limit - flow, w)); int k = dinic(v, std::min(limit - flow, w));
if (!k) d[v] = 0; if (!k) d[v] = 0;
flow += k;
edge[i] -= k; edge[i] -= k;
edge[i ^ 1] += k; edge[i ^ 1] += k;
flow += k;
} }
} }
@ -78,7 +80,7 @@ int main() {
std::ios::sync_with_stdio(false); std::ios::sync_with_stdio(false);
cin.tie(nullptr); cin.tie(nullptr);
std::fill_n(head, N << 1, -1); std::fill(std::begin(head), std::end(head), -1);
cin >> n >> m >> e; cin >> n >> m >> e;
@ -97,15 +99,17 @@ int main() {
for (int i = 1, u, v; i <= e; i++) { for (int i = 1, u, v; i <= e; i++) {
cin >> u >> v; cin >> u >> v;
add(u, n + v, 1); add(u, v + n, 1);
add(n + v, u, 0); add(v + n, u, 0);
} }
int res = 0;
while (bfs()) { while (bfs()) {
while (flow = dinic(s, INF)) ans += flow; while (int flow = dinic(s, INF)) res += flow;
} }
cout << ans << endl; cout << res << endl;
return 0; return 0;
} }