http://blog.163.com/huangbingliang@yeah/blog/static/94161399201011291044527/
复杂度O(n^3)。
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int N = 305;
const int Inf = 1e9;
int top,match[N];
int n,fix,w[N][N],va[N],vb[N];
bool visx[N],visy[N];
bool dfs(int u)
{
visx[u] = true;
for(int v=1;v<=n;v++)
{
if(visy[v])
continue;
if(va[u]+vb[v] == w[u][v])
{
visy[v] = true;
if(!match[v] || dfs(match[v]))
{
match[v] = u;
return true;
}
}
else
fix = min(fix,va[u]+vb[v]-w[u][v]);
}
return false;
}
int KM()
{
memset(vb,0,sizeof(vb));
memset(match,0,sizeof(match));
for(int i=1;i<=n;i++)
{
while(1)
{
memset(visx,false,sizeof(visx));
memset(visy,false,sizeof(visy));
fix = Inf;
if(dfs(i))
break;
if(fix == Inf)
return -1;
for(int i=1;i<=n;i++)
{
if(visx[i])
va[i] -= fix;
if(visy[i])
vb[i] += fix;
}
}
}
int res = 0;
for(int i=1;i<=n;i++)
res += va[i] + vb[i];
return res;
}
int main()
{
while(~scanf("%d",&n))
{
memset(va,0,sizeof(va));
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
{
scanf("%d",&w[i][j]);
va[i] = max(va[i],w[i][j]);
}
printf("%d\n",KM());
}
return 0;
}