匈牙利算法,优点:代码短
邻接矩阵:复杂度 (O(n^3)) 。邻接表:复杂度 (O(nm)) 。
/*
nx X侧顶点的数量
ny Y侧顶点的数量
vis 顶点i是否在交错路中
cx X侧顶点i匹配的Y侧顶点
cy Y侧顶点i匹配的X侧顶点
*/
const int MAXN = 500 + 10;
int nx, ny;
int G[MAXN][MAXN];
bool vis[MAXN];
int cx[MAXN], cy[MAXN];
int dfs(int u) {
for (int v = 1; v <= ny; ++v) {
if (G[u][v] && !vis[v]) {
vis[v] = 1;
if (!cy[v] || dfs(cy[v])) {
cx[u] = v, cy[v] = u;
return 1;
}
}
}
return 0;
}
int hungarian() {
memset(cx, 0, sizeof(cx[0]) * (nx + 1));
memset(cy, 0, sizeof(cy[0]) * (ny + 1));
int res = 0;
for (int i = 1; i <= nx; ++i) {
if (!cx[i]) {
memset(vis, 0, sizeof(vis[0]) * (ny + 1));
res += dfs(i);
}
}
return res;
}
void solve() {
int m;
scanf("%d%d%d", &nx, &ny, &m);
memset(G, 0, sizeof(G));
for (int i = 1; i <= m; ++i) {
int u, v;
scanf("%d%d", &u, &v);
G[u][v] = 1;
}
printf("%d
", hungarian());
}