【模板】二分图匹配

题面

题解

这题被我强行用来练习网络流…

建立源点和汇点,连接二分图的两边,跑最大流即可。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include<bits/stdc++.h>
#define RG register
#define clear(x, y) memset(x, y, sizeof(x));
using namespace std;

inline int read()
{
int data=0, w=1;
char ch=getchar();
while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
if(ch=='-') w=-1, ch=getchar();
while(ch>='0'&&ch<='9') data=(data<<3)+(data<<1)+(ch^48), ch=getchar();
return data*w;
}

const int maxn(2020), maxm(1000010);
struct edge { int next, to, cap; } e[maxm << 1];
int head[maxn], e_num = -1, n, m, s, t, E;

inline void add_edge(int from, int to, int cap)
{
e[++e_num] = (edge) {head[from], to, cap};
head[from] = e_num;
}

inline void add(int from, int to, int cap)
{
add_edge(from, to, cap);
add_edge(to, from, 0);
}

int lev[maxn], cur[maxn], q[maxn], tail;
inline int bfs()
{
clear(lev, 0); q[tail = lev[s] = 1] = s;
for(int h = 1; h <= tail; h++)
{
int x = q[h];
for(RG int i = head[x]; ~i; i = e[i].next)
{
int to = e[i].to;
if(lev[to] || (!e[i].cap)) continue;
lev[to] = lev[x] + 1; q[++tail] = to;
}
}
return lev[t];
}

int dfs(int x, int f)
{
if(x == t) return f;
RG int ans = 0, cap;
for(RG int &i = cur[x]; ~i; i = e[i].next)
{
int to = e[i].to;
if(e[i].cap && lev[to] == lev[x] + 1)
{
cap = dfs(to, min(f - ans, e[i].cap));
e[i].cap -= cap; e[i ^ 1].cap += cap;
ans += cap;
if(ans == f) break;
}
}
return ans;
}

inline int Dinic()
{
RG int ans = 0;
while(bfs())
{
for(RG int i = 1; i <= n + m + 2; i++) cur[i] = head[i];
ans += dfs(s, INT_MAX);
}
return ans;
}

int main()
{
clear(head, -1); n = read(); m = read(); E = read(); s = 1; t = n + m + 2;
for(RG int i = 1, a, b; i <= E; i++)
{
a = read(); b = read();
if(b > m || a > n) continue;
add(a + 1, b + n + 1, 1);
}
for(RG int i = 1; i <= n; i++) add(s, i + 1, 1);
for(RG int i = 1; i <= m; i++) add(i + n + 1, t, 1);
printf("%d\n", Dinic());
return 0;
}
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×