forked from bnslakki/Spoj
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMATCHING.cpp
77 lines (71 loc) · 1.31 KB
/
MATCHING.cpp
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
#include "bits/stdc++.h"
using namespace std;
const int maxn = 100001;
vector<int> arr[maxn];
int match[maxn], dist[maxn];
int n, m;
bool bfs(){
int u, v;
queue<int> q;
for(int i = 1; i <= n; i++){
if(!match[i]){
dist[i] = 0;
q.push(i);
}
else dist[i] = INT_MAX;
}
dist[0] = INT_MAX;
while(!q.empty()){
u = q.front();
q.pop();
if(u){
for(int i = 0; i < arr[u].size(); i++){
v = arr[u][i];
if(dist[match[v]] == INT_MAX){
dist[match[v]] = dist[u] + 1;
q.push(match[v]);
}
}
}
}
return (dist[0] != INT_MAX);
}
bool dfs(int u){
if(u){
for(int i = 0; i < arr[u].size(); i++){
int v = arr[u][i];
if(dist[match[v]] == dist[u] + 1){
if(dfs(match[v])){
match[v] = u;
match[u] = v;
return 1;
}
}
}
dist[u] = INT_MAX;
return 0;
}
return 1;
}
int HopcroftKarp(){
int matching = 0;
fill(match, match+n+m+1, 0);
while(bfs()){
for(int i = 1; i <= n; i++){
if(!match[i] && dfs(i))
matching++;
}
}
return matching;
}
int main(){
//freopen("t.txt", "r", stdin);
int u, v, p;
scanf("%d %d %d",&n, &m, &p);
for(int i = 0; i < p; i++){
scanf("%d %d",&u, &v);
arr[u].push_back(v + n);
arr[v + n].push_back(u);
}
printf("%d\n",HopcroftKarp());
}