题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=2255
思路:比较裸的KM算法
KM算法讲解的一些地址:
主要思想:http://wenku.baidu.com/view/28203c49767f5acfa1c7cd38.html
主要过程:http://wenku.baidu.com/link?url=rspbEQ6PFDsAQz_zJNjSEE97w3qR1XWWofOekHT0y15VAyBADwFEaUh5KGbcl-e2Ddgbn3UpvTCLrQwX4H4deoIkQfXTeIW6sBO9nAGh7sG
代码过程详解:http://wenku.baidu.com/link?url=oUbIxhSFz_PFzGb-M1TRuA9DG8Ip4STaXmqW4g39zw2xPwHfGO2B4jgt0Z5VA7NT1RX5tu7k0QjVTJDZg-IzV02jmlQvQN8H0zgUtt2eGO7
代码:http://blog.csdn.net/niushuai666/article/details/7171525
AC代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x3f3f3f3f;//1061109567
typedef long long ll;
const int maxn = 310;
const int mod = 1000007;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
using namespace std;
int map1[maxn][maxn];
bool visitx[maxn],visity[maxn];
int match[maxn];
int lx[maxn],ly[maxn];
int n;
bool find1(int u)
{
visitx[u] = true;
for(int i=0; i<n; i++)
{
if(!visity[i] && lx[u] + ly[i] == map1[u][i])
{
visity[i] = true;
if(match[i] == -1 || find1(match[i]))//注意是等于-1
{
match[i] = u;
return true;
}
}
}
return false;
}
void km()
{
memset(lx,0,sizeof(lx));
memset(ly,0,sizeof(ly));
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
lx[i] = max(lx[i],map1[i][j]);
}
}
memset(match,-1,sizeof(match));
for(int k=0; k<n; k++)//对n个点进行分配
{
while(1)
{
memset(visitx,false,sizeof(visitx));
memset(visity,false,sizeof(visity));
if(find1(k))
break;
else
{
int temp = INT_MAX;
for(int i=0; i<n; i++)//x在交叉树内
{
if(visitx[i])
{
for(int j=0; j<n; j++)//y在交叉树外
{
if(!visity[j] && temp > lx[i] + ly[j] - map1[i][j])
temp = lx[i] + ly[j] - map1[i][j];
}
}
}
for(int i=0; i<n; i++)
{
if(visitx[i])
lx[i] -= temp;
if(visity[i])
ly[i] += temp;
}
}
}
}
}
int main()
{
while(scanf("%d",&n) != EOF)
{
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
scanf("%d",&map1[i][j]);
}
}
km();
int sum = 0;
for(int i=0; i<n; i++)
{
sum += map1[match[i]][i];
}
printf("%d\n",sum);
}
return 0;
}