-
Notifications
You must be signed in to change notification settings - Fork 697
/
Matching (Hopcroft-Karp) in Bipartite Graph.cpp
90 lines (78 loc) · 1.37 KB
/
Matching (Hopcroft-Karp) in Bipartite Graph.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
//1 indexed Hopcroft-Karp Matching in O(E sqrtV)
struct Hopcroft_Karp
{
static const int inf = 1e9;
int n;
vector<int> matchL, matchR, dist;
vector<vector<int> > g;
Hopcroft_Karp(int n) :
n(n), matchL(n+1), matchR(n+1), dist(n+1), g(n+1) {}
void addEdge(int u, int v)
{
g[u].push_back(v);
}
bool bfs()
{
queue<int> q;
for(int u=1;u<=n;u++)
{
if(!matchL[u])
{
dist[u]=0;
q.push(u);
}
else
dist[u]=inf;
}
dist[0]=inf;
while(!q.empty())
{
int u=q.front();
q.pop();
for(auto v:g[u])
{
if(dist[matchR[v]] == inf)
{
dist[matchR[v]] = dist[u] + 1;
q.push(matchR[v]);
}
}
}
return (dist[0]!=inf);
}
bool dfs(int u)
{
if(!u)
return true;
for(auto v:g[u])
{
if(dist[matchR[v]] == dist[u]+1 &&dfs(matchR[v]))
{
matchL[u]=v;
matchR[v]=u;
return true;
}
}
dist[u]=inf;
return false;
}
int max_matching()
{
int matching=0;
while(bfs())
{
for(int u=1;u<=n;u++)
{
if(!matchL[u])
if(dfs(u))
matching++;
}
}
return matching;
}
};
//Problem 1: https://codeforces.com/contest/387/problem/D
//Solution 1: https://codeforces.com/contest/387/submission/48378847
//Problem 2 (Ensuring that matching is consistent): https://www.spoj.com/problems/ADABLOOM/
//Solution 2:http://p.ip.fi/igSb
//Problem 3: https://codeforces.com/gym/101853/problem/B