题目来源:http://poj.org/problem?id=3041
匹配的相关概念及定理见:https://blog.csdn.net/moon_sky1999/article/details/81331795
可以等价为二分图中求最小顶点覆盖,由相关定理可得,最小顶点覆盖等于最大匹配,因此只需用匈牙利算法求出最大匹配即可。
代码:
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
int n,k,from[555];
bool vis[555];
vector <int> v[555];
bool match(int x) {
for (int i = 0; i < v[x].size(); ++i) {
int u=v[x][i];
if (vis[u] == 0) {
vis[u] = 1;
if (from[u] == -1 || match(from[u])) {
from[u] = x;
return 1;
}
}
}
return 0;
}
int hungry() {
int tot = 0;
memset(from, -1, sizeof(from));
for (int i = 1; i <= n; ++i) {
memset(vis, 0, sizeof(vis));
if (match(i))
++tot;
}
return tot;
}
int main() {
while (~scanf("%d%d", &n, &k)) {
for (int i = 1; i <= n; ++i)
v[i].clear();
int x, y;
for (int i = 1; i <= k; ++i) {
scanf("%d%d", &x, &y);
v[x].push_back(y);
}
int cnt = hungry();
printf("%d\n", cnt);
}
return 0;
}