forked from wisdompeak/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
b9ebf4f
commit c3aa7c0
Showing
1 changed file
with
53 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
// https://www.renfei.org/blog/bipartite-matching.html | ||
// 顶点、边的编号均从 0 开始 | ||
// 邻接表储存 | ||
|
||
struct Edge | ||
{ | ||
int from; | ||
int to; | ||
int weight; | ||
|
||
Edge(int f, int t, int w):from(f), to(t), weight(w) {} | ||
}; | ||
|
||
vector<int> G[__maxNodes]; /* G[i] 存储顶点 i 出发的边的编号 */ | ||
vector<Edge> edges; | ||
typedef vector<int>::iterator iterator_t; | ||
int num_nodes; | ||
int num_left; | ||
int num_right; | ||
int num_edges; | ||
int matching[__maxNodes]; /* 存储求解结果 */ | ||
int check[__maxNodes]; | ||
|
||
bool dfs(int u) | ||
{ | ||
for (iterator_t i = G[u].begin(); i != G[u].end(); ++i) { // 对 u 的每个邻接点 | ||
int v = edges[*i].to; | ||
if (!check[v]) { // 要求不在交替路中 | ||
check[v] = true; // 放入交替路 | ||
if (matching[v] == -1 || dfs(matching[v])) { | ||
// 如果是未盖点,说明交替路为增广路,则交换路径,并返回成功 | ||
matching[v] = u; | ||
matching[u] = v; | ||
return true; | ||
} | ||
} | ||
} | ||
return false; // 不存在增广路,返回失败 | ||
} | ||
|
||
int hungarian() | ||
{ | ||
int ans = 0; | ||
memset(matching, -1, sizeof(matching)); | ||
for (int u=0; u < num_left; ++u) { | ||
if (matching[u] == -1) { | ||
memset(check, 0, sizeof(check)); | ||
if (dfs(u)) | ||
++ans; | ||
} | ||
} | ||
return ans; | ||
} |