DFS实现,适用于稠密图:(复杂度O(VE))
#include<bits/stdc++.h>
using namespace std;
const int mx = 105;
vector<int> G[mx];
int match[mx]; ///match表示匹配的对象编号
bool vis[mx];
bool dfs(int i)
{
vis[i] = true;
for (int j = 0; j < G[i].size(); ++j)
{
int v = G[i][j], mv = match[v];
if (mv < 0 || !vis[mv] && dfs(mv))
{
match[v] = mv;
match[mv] = v;
return true;
}
}
return false;
}
///返回匹配的对数
int maxmatch(int n)
{
int ans = 0;
memset(match, -1, sizeof(match));
for (int i = 0; i < n; ++i)
if (match[i] < 0)
{
memset(vis, 0, sizeof(vis));
if (dfs(i)) ++ans;
}
return ans;
}
BFS实现,适用于稀疏图:(复杂度O(V^3))
#include<bits/stdc++.h>
using namespace std;
const int mx = 105;
int G[mx][mx];
int cx[mx], cy[mx]; ///匹配的对象编号
int pred[mx]; /// 记录交错轨和标记Y集合中访问过的点
int q[mx]; ///queue
int maxmatch(int nx, int ny)
{
int ans = 0, y, sta, fin, i, j;
memset(cx, -1, sizeof(cx));
memset(cy, -1, sizeof(cy));
for (i = 0; i < nx; ++i)
{
if (cx[i] != -1) continue;
///对x中的每个未盖点i执行一次bfs找交错轨
fill(pred, pred + ny, -2); ///初始值
sta = fin = 0;
for (j = 0; j < ny; ++j) ///把i的邻接点加入队列
if (G[i][j])
{
pred[j] = -1; ///-1表示遍历到,是邻接点
q[fin++] = j;
}
while (sta < fin) ///BFS
{
y = q[sta];
if (cy[y] == -1) break; ///找到了一个未匹配点,即找到了一条交错轨
///若没break说明y已经被匹配给了cy[y]了
++sta;
for (j = 0; j < ny; ++j)
if (pred[j] == -2 && G[cy[y]][j]) ///从cy[y]出发,将它的邻接顶点加入队列
{
pred[j] = y;
q[fin++] = j;
}
}
if (sta == fin) continue; ///未找到交错轨
while (pred[y] >= 0) ///更改交错轨上的匹配状态
{
cx[cy[pred[y]]] = y;
cy[y] = cy[pred[y]];
y = pred[y];
}
cx[i] = y, cy[y] = i;
++ans;
}
return ans;
}