/*
二分图最优匹配算法,邻接矩阵形式
复杂度o(m^3)
HDU 2255
当前默认权值最大匹配
*/
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<string>
#include<vector>
#include<queue>
#include<ctype.h>
#include<bitset>
#include<map>
# pragma comment (linker,"/STACK:16777216")
using namespace std;
const int MAXN = 305;
const int INF = 2100000000;
const double esp = 1e-9;
int n;
int mat[MAXN][MAXN];//图
int link[MAXN], slack[MAXN], lx[MAXN], ly[MAXN];
//link记录最有匹配中x节点对应的y节点
//slack松弛量数组
//lx, ly分别是x集合和y集合中点的顶标
bool visx[MAXN], visy[MAXN];
//标记点是否访问
//在相等子图中查找一条增广路径
bool find(int x)
{
visx[x] = 1;
for(int i = 1; i <= n; i++)
{
int temp = lx[x] + ly[i] - mat[x][i];
if(visy[i]) continue;
//只有满足相等子图时才能进行增广
if(temp == 0)
{
visy[i] = 1;
if(link[i] == 0 || find(link[i]))
{
link[i] = x;
return 1;
}
}
//非相等子图,更新松弛量数组
else slack[i] = min(temp, slack[i]);
}
return 0;
}
void km(int n)
{
memset(link, 0, sizeof(link));
memset(ly, 0, sizeof(ly));
memset(lx, 0, sizeof(lx));
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
lx[i] = max(lx[i], mat[i][j]);//初始化顶标
/*
如果查找最小权匹配,改成这样
for(int i = 1; i <= n; i++)
{
lx[i] = -INF;
for(int j = 1; j <= m; j++)
lx[i] = max(lx[i], mat[i][j]);
}
*/
for(int i = 1; i <= n; i++)
{
memset(slack, 127, sizeof(slack));
while(1)
{
memset(visx, 0, sizeof(visx));
memset(visy, 0, sizeof(visy));
if(find(i)) break;//找到相等子图的一个增广匹配,退出
int d = INF;
for(int j = 1; j <= n; j++)
if(!visy[j]) d = min(d, slack[j]);//找不到相等子图的增广匹配,选取最小的顶标与边权差修改顶标
for(int j = 1; j <= n; j++)//在交错树中的x,顶标值减去d
if(visx[j]) lx[j] -= d;
for(int j = 1; j <= n; j++)//在交错树中的y,顶标值加上d
if(visy[j]) ly[j] += d;
else slack[j] -= d;//不在交错树中的y,由于对应的x顶标减少d,slack值也减少d
}
}
}
int main()
{
//freopen("C:/Users/zts/Desktop/in.txt", "r", stdin);
while(cin >> n)
{
memset(mat, 0, sizeof(mat));
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
cin >> mat[i][j];
km(n);
int ans = 0;
for(int i = 1; i <= n; i++)
{
if(link[i] != 0)
ans += mat[link[i]][i];
}
cout << ans << endl;
}
return 0;
}
KM算法模板 hdu2255
最新推荐文章于 2019-10-25 18:33:29 发布