算法思路:网络流, 模板题。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<climits>
#include<algorithm>
using namespace std;
#define N 310
int map[N][N];
bool visitx[N], visity[N];
int lx[N], ly[N];
int match[N];
int n;
bool Hungary(int u) //匈牙利算法
{
visitx[u] = true;
for(int i = 0; i < n; ++i)
{
if(!visity[i] && lx[u] + ly[i] == map[u][i])
{
visity[i] = true;
if(match[i] == -1 || Hungary(match[i]))
{
match[i] = u;
return true;
}
}
}
return false;
}
void KM_perfect_match()
{
int temp;
memset(lx, 0, sizeof(lx)); //初始化顶标
memset(ly, 0, sizeof(ly)); //ly[i]为0
for(int i = 0; i < n; ++i) //lx[i]为权值最大的边
for(int j = 0; j < n; ++j)
lx[i] = max(lx[i], map[i][j]);
for(int i = 0; i < n; ++i) //对n个点匹配
{
while(1)
{
memset(visitx, false, sizeof(visitx));
memset(visity, false, sizeof(visity));
if(Hungary(i)) //匹配成功
break;
else //匹配失败,找最小值
{
temp = INT_MAX;
for(int j = 0; j < n; ++j) //x在交错树中
if(visitx[j])
for(int k = 0; k < n; ++k) //y在交错树外
if(!visity[k] && temp > lx[j] + ly[k] - map[j][k])
temp = lx[j] + ly[k] - map[j][k];
for(int j = 0; j < n; ++j) //更新顶标
{
if(visitx[j])
lx[j] -= temp;
if(visity[j])
ly[j] += temp;
}
}
}
}
}
int main()
{
int ans;
while(scanf("%d", &n) != EOF)
{
ans = 0;
memset(match, -1, sizeof(match));
for(int i = 0; i < n; ++i)
for(int j = 0; j < n; ++j)
scanf("%d", &map[i][j]);
KM_perfect_match();
for(int i = 0; i < n; ++i) //权值相加
ans += map[match[i]][i];
printf("%d\n", ans);
}
return 0;
}
转载自: http://blog.csdn.net/niushuai666/article/details/7171525