以下一些链接是大佬写的,写的很好,大家可以看看:
https://blog.youkuaiyun.com/dark_scope/article/details/8880547
https://blog.youkuaiyun.com/c20180630/article/details/70175814
http://www.renfei.org/blog/bipartite-matching.html
【code】
下面是匈牙利算法的DFS版:
#include"stdafx.h"
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
using namespace std;
const int maxn = 1e5;
const int INF = 1e9;
int vertexnum;//顶点数(男方顶点数)
vector<int>adj[maxn];//邻接表存储图
bool vis[maxn];//记录顶点在不在增广路中(或者有没有被访问)
int match[maxn];//match[v]=-1标记妹子v没有匹配到情侣,match[v]=u表示妹子v匹配到的情侣为u
bool find(int u) {//找从u出发有没有增广路
for (int i = 0; i < adj[u].size(); i++) {
int v = adj[u][i];
if (vis[v] == false) {//如果顶点v没有被访问(不在增广路中)
vis[v] = true;
if (match[v] == -1 || find(match[v])) {//如果v还没有情侣 或 v的原情侣还可以找到其它妹子撮合
match[v] = u;//置妹子v的情侣为u
return true;
}
}
}
//注意这里不需置vis[v]=false进行回溯,为什么呢?(联系一下匈牙利树)
return false;//没找到
}
int matching() {//匈牙利匹配算法
int maxnum = 0;
fill(match, match + maxn, -1);
for (int i = 1; i <= vertexnum; i++) {
fill(vis, vis + maxn, false);
if (find(i) == true) maxnum++;
}
return maxnum;
}
int main() {
cin >> vertexnum;
for (int i = 0; i < vertexnum; i++) {
int vertex1, vertex2;
int k;//表示vertex1和k个顶点有联系
cin >> vertex1 >> k;
for (int i = 0; i < k; i++) {//输入k个与vertex1有联系的vertex2
cin >> vertex2;
adj[vertex1].push_back(vertex2);
}
}
cout << matching();
return 0;
}
下面是匈牙利算法的BFS版(将上面find函数的递归改成了非递归)
bool find(int u) {
stack<int> s;
s.push(u);
while (!s.empty()) {//找从u出发的增广路,并匹配
int uu = s.top();
s.pop();
int num = 0;
for (int i = 0; i < adj[uu].size(); i++) {//将u有好感度的妹子全部入栈
int vv = adj[uu][i];
if (vis[vv] == false) {
num++;
s.push(vv);
}
}
for (int i = 0; i < num; i++) {//将u有好感度的妹子依次出栈进行校验
int vv = s.top();
s.pop();
vis[vv] = true;
if (match[vv] == -1) {//如果vv妹子还没有情侣,则u和vv配对成功
match[vv] = u;
return true;//找到匹配
}
else {//如果vv妹子有情侣,则将vv妹子的原情侣match[vv]入栈(相当于递归)
s.push(match[vv]);
break;
}
}
}
return false;//没找到匹配则返回false
}