二分图的最大匹配
无权二分图
匈牙利算法
find寻找已有匹配M的一条可扩路,如果找到则有更大匹配M*
#include<iostream>
#include<cstring>
using namespace std;
const int N = 210;
int g[N][N];
int match[N];
//bool usex[M];
bool usey[N];
int m, n;
bool find(int x){
// usex[x] = true;
for(int i = 1; i <= n; ++i){
if(g[x][i] && !use[i]){
usey[i] = true;
if(!match[i] || find(match[i])){
match[i] = x;
return true;
}
}
}
return false;
}
int main(){
memset(g[0], 0, sizeof(g));
memset(match, 0, sizeof(match));
cin >> m >> n;
int t, k;
for(int i = 1; i <= m; ++i){
cin >> t;
for(int j = 0 ; j < t; ++j){
cin >> k;
g[i][k] = 1;
}
}
int res = 0;
for(int i = 1; i <= m; ++i){
// memset(usex, false, sizeof(usex));
memset(usey, false, sizeof(usey));
if(find(i)) ++res;
}
cout << res << endl;
return 0;
}
带权二分图(求最大权匹配)
KM算法
可行顶点标号lx[M], ly[N], 满足任意点(x, y)都有lx[x]+ly[y]>=w[x][y],取初值ly[y]=0, lx[x]=max(w[x][y]).
对任意满足lx[x]+ly[y]==w[x][y]的边集的相等子图,执行匈牙利算法
若find返回假。则对当前usex[x]==true && usey[y]==false的所有点对(x, y),d = min(lx[x]+ly[y]-w[x][y])。
对任意usex[x] == true, lx[x] -= d;
对任意usey[y] == true, ly[y] += d;
继续find(x)直到返回真
若find返回真,find(x+1)查找x+1的匹配
#include<iostream>
#include<cstring>
using namespace std;
const int INF = 1e9;
const int N = 210;
int g[N][N];
int match[N];
int lx[N];
int ly[N];
bool usey[N];
bool usex[N];
int m, n;
bool find(int x){
usex[x] = true;
for(int i = 1; i <= n; ++i){
if(!usey[i] && lx[x]+ly[i] == g[x][i]){
usey[i] = true;
if(!match[i] || find(match[i])){
match[i] = x;
return true;
}
}
}
return false;
}
int main(){
memset(g[0], 0, sizeof(g));
memset(match, 0, sizeof(match));
memset(lx, 0, sizeof(lx));
memset(ly, 0, sizeof(ly));
cin >> m >> n;
for(int i = 1; i <= m; ++i){
for(int j = 1 ; j <= n; ++j){
cin >> g[i][j];
lx[i] = max(lx[i], g[i][j]);
}
}
for(int i = 1; i <= m; ++i){
memset(usex, false, sizeof(usex));
memset(usey, false, sizeof(usey));
while(!find(i)){
int d = INF;
for(int x = 1; x <= m; ++x){
if(usex[x]){
for(int y = 1; y <= n; ++y){
if(!usey[y]) d = min(d, lx[x]+ly[y]-g[x][y]);
}
}
}
for(int x = 1; x <= m; ++x) if(usex[x]) lx[x] -= d;
for(int y = 1; y <= n; ++y) if(usey[y]) ly[y] += d;
memset(usex, false, sizeof(usex));
memset(usey, false, sizeof(usey));
}
}
int maxWeight = 0;
for(int i = 1; i <= m; ++i) maxWeight += lx[i];
for(int i = 1; i <= n; ++i) maxWeight += ly[i];
cout << "max weight = " << maxWeight << endl;
for(int i = 1; i <= n; ++i) cout << match[i] << " matched " << i << endl;
return 0;
}