-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathHopcroft Karp.cpp
111 lines (93 loc) · 1.88 KB
/
Hopcroft Karp.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
vector< int > graph[MAX];
int n, m, match[MAX], dist[MAX];
int NIL=0;
bool bfs()
{
int i, u, v, len;
queue< int > Q;
for(i=1; i<=n; i++)
{
if(match[i]==NIL)
{
dist[i] = 0;
Q.push(i);
}
else dist[i] = INF;
}
dist[NIL] = INF;
while(!Q.empty())
{
u = Q.front(); Q.pop();
if(u!=NIL)
{
len = graph[u].size();
for(i=0; i<len; i++)
{
v = graph[u][i];
if(dist[match[v]]==INF)
{
dist[match[v]] = dist[u] + 1;
Q.push(match[v]);
}
}
}
}
return (dist[NIL]!=INF);
}
bool dfs(int u)
{
int i, v, len;
if(u!=NIL)
{
len = graph[u].size();
for(i=0; i<len; i++)
{
v = graph[u][i];
if(dist[match[v]]==dist[u]+1)
{
if(dfs(match[v]))
{
match[v] = u;
match[u] = v;
return true;
}
}
}
dist[u] = INF;
return false;
}
return true;
}
int hopcroft_karp()
{
int matching = 0, i;
// match[] is assumed NIL for all vertex in graph
// All nodes on left and right should be distinct
while(bfs())
for(i=1; i<=n; i++)
if(match[i]==NIL && dfs(i))
matching++;
return matching;
}
void clear()
{
FOR(j,0,MAX) graph[j].clear();
ms(match,NIL);
}
int main()
{
// ios_base::sync_with_stdio(0);
// cin.tie(NULL); cout.tie(NULL);
// freopen("in.txt","r",stdin);
// SPOJ - Fast Maximum Matching
int p, x, y;
scanf("%d%d%d", &n, &m, &p);
FOR(i,0,p)
{
scanf("%d%d", &x, &y);
graph[x].pb(n+y);
graph[n+y].pb(x);
}
printf("%d\n", hopcroft_karp());
return 0;
}