二分图的最大匹配
代码
#include <bits/stdc++.h>
using namespace std;const int N = 505, M = 100005;
int h[N], e[M], ne[M], idx;
int match[N];
bool st[N];
int n1, n2, m;void add(int a, int b)
{e[idx] = b; //e[idx]存放的是第idx条边的终点ne[idx] = h[a]; //ne[idx]存放的是与a结点相连的下一条边h[a] = idx++; //把当前这条边放入
}bool find(int x)
{for (int i = h[x]; i != -1; i = ne[i]){int j = e[i];if (!st[j]){st[j] = true;if (match[j] == 0 || find(match[j])){match[j] = x;return true;}}}return false;
}int main()
{cin >> n1 >> n2 >> m;memset(h, -1, sizeof h); // 将所有结点连接的边初始化为-1while (m--){int a, b;cin >> a >> b;add(a, b); //将每个边加入到邻接表中}int ans = 0;for (int i = 1; i <= n1; i++){memset(st, false, sizeof st); //每次都要初始化每个女孩的状态,避免递归出现死循环if (find(i)) //如果当前左节点匹配右节点成功ans++;}cout << ans << endl;return 0;
}