把所有点的x,y坐标作为二分图的U和V,并将这个问题转化为寻找二分图的最小顶点覆盖。
对于二分图而言,|最大匹配| = |最小顶点覆盖|。
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
const int maxn = 1000 + 10;
int n;
vector<int> G[maxn];
int match[maxn];
bool used[maxn];
void add_edge(int u, int v) {
G[u].push_back(v);
G[v].push_back(u);
}
bool Dfs(int v) {
used[v] = true;
for (int i = 0; i < G[v].size(); i++) {
int u = G[v][i], w = match[u];
if (w < 0 || (!used[w] && Dfs(w))) {
match[v] = u;
match[u] = v;
return true;
}
}
return false;
}
int Hungarian() {
int res = 0;
memset(match, -1, sizeof(match));
for (int v = 0; v < n; v++) {
if (match[v] < 0) {
memset(used, 0, sizeof(used));
if (Dfs(v)) {
res++;
}
}
}
return res;
}
int main()
{
int k;
cin >> n >> k;
for (int i = 0; i < k; i++) {
int r, c;
cin >> r >> c;
add_edge(r-1, n+c-1);
}
cout << Hungarian() << endl;
return 0;
}