0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-09-16 19:45:24 +00:00

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

https://www.luogu.com.cn/record/91953452
This commit is contained in:
Baoshuo Ren 2022-10-28 21:18:23 +08:00
parent f38e430d75
commit c968af6487
Signed by: baoshuo
GPG Key ID: 00CB9680AB29F51A
3 changed files with 84 additions and 15 deletions

View File

@ -1,45 +1,108 @@
#include <iostream>
#include <array>
#include <vector>
#include <algorithm>
#include <queue>
using std::cin;
using std::cout;
const char endl = '\n';
const int N = 505;
const int N = 505,
M = 5e4 + 5;
const int INF = 0x3f3f3f3f;
int n, m, e, tag[N], match[N], ans;
std::array<std::vector<int>, N> g;
int n, m, e, s, t, flow, ans;
int idx, head[N << 1], ver[M << 2], edge[M << 2], next[M << 2];
int d[N << 1], cur[N << 1];
bool dfs(int u, int t) {
if (tag[u] == t) return false;
void add(int u, int v, int w) {
next[idx] = head[u];
ver[idx] = v;
edge[idx] = w;
head[u] = idx++;
}
tag[u] = t;
bool bfs() {
std::fill_n(d, N << 1, 0);
for (int v : g[u]) {
if (!match[v] || dfs(match[v], t)) {
match[v] = u;
return true;
std::queue<int> q;
q.emplace(s);
d[s] = 1;
cur[s] = head[s];
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = head[u]; ~i; i = next[i]) {
int v = ver[i],
w = edge[i];
if (w && !d[v]) {
d[v] = d[u] + 1;
cur[v] = head[v];
if (v == t) return true;
q.emplace(v);
}
}
}
return false;
}
int dinic(int u, int limit) {
if (u == t) return limit;
int flow = 0;
for (int i = cur[u]; ~i && flow < limit; i = next[i]) {
cur[u] = i;
int v = ver[i],
w = edge[i];
if (w && d[v] == d[u] + 1) {
int k = dinic(v, std::min(limit - flow, w));
if (!k) d[v] = 0;
edge[i] -= k;
edge[i ^ 1] += k;
flow += k;
}
}
return flow;
}
int main() {
std::ios::sync_with_stdio(false);
cin.tie(nullptr);
std::fill_n(head, N << 1, -1);
cin >> n >> m >> e;
s = 0, t = n + m + 1;
for (int i = 1; i <= n; i++) {
add(s, i, 1);
add(i, s, 0);
}
for (int i = 1; i <= m; i++) {
add(n + i, t, 1);
add(t, n + i, 0);
}
for (int i = 1, u, v; i <= e; i++) {
cin >> u >> v;
g[u].emplace_back(v);
add(u, n + v, 1);
add(n + v, u, 0);
}
for (int i = 1; i <= n; i++) {
if (dfs(i, i)) ans++;
while (bfs()) {
while (flow = dinic(s, INF)) ans += flow;
}
cout << ans << endl;

BIN
Luogu/P3386/data/P3386_5.in (Stored with Git LFS) Normal file

Binary file not shown.

BIN
Luogu/P3386/data/P3386_5.out (Stored with Git LFS) Normal file

Binary file not shown.