二分图的最大匹配(模板)
二分图的最大匹配算法模板,复杂度是O(V*E),有关二分图匹配的算法详解
趣写算法系列之–匈牙利算法
const int maxn = 105;
int k, m, n;
int girl[maxn];//girl[i]等于第i个女生匹配到的男生
int line[maxn][maxn];//line[i][j]表示男生i喜欢女生j
bool used[maxn];
//为男生x匹配一个女生,成功返回true,失败返回false
//注意在调用这个函数之前每次都要used[]数组清零
bool match(int x) {
for (int i = 1; i <= n; ++i) {
if (line[x][i] && !used[i]) {
used[i] = true;
if (girl[i] == 0 || match(girl[i])) {
girl[i] = x;
return true;
}
}
}
return false;
}
模板题 hdu2063 http://acm.hdu.edu.cn/showproblem.php?pid=2063
#include<bits/stdc++.h>
using namespace std;
const int maxn = 550;
int k, m, n;
int girl[maxn];
int line[maxn][maxn];
bool used[maxn];
bool match(int x) {
for (int i = 1; i <= n; ++i) {
if (line[x][i] && !used[i]) {
used[i] = true;
if (girl[i] == 0 || match(girl[i])) {
girl[i] = x;
return true;
}
}
}
return false;
}
int main() {
while (scanf("%d", &k) == 1 && k) {
scanf("%d%d", &m, &n);
memset(girl, 0, sizeof(girl));
memset(line, 0, sizeof(line));
for (int i = 0; i < k; ++i) {
int u, v;
scanf("%d%d", &u, &v);
line[u][v] = 1;
}
int ans = 0;
for (int i = 1; i <= m; ++i) {
memset(used, 0, sizeof(used));
if (match(i)) ++ans;
}
printf("%d\n", ans);
}
return 0;
}