这题使我对km多了一些看法

写给自己看。。

km结束后bx[i] + by[j] == w[i][j], 所以所有bx与by的和即为w的和

而且记住bx[i] + by[j] >= w[i][j] 这个式子 那么bx与by的最小值 即为km结束后的值

#include <iostream>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <algorithm>
#include <vector>
#define mem(a, b) memset(a, b, sizeof(a))
using namespace std;
const int maxn = , INF = 0x7fffffff;
int usedx[maxn], usedy[maxn], w[maxn][maxn], bx[maxn], by[maxn], cx[maxn], cy[maxn];
int nx, ny, n, minn, min_value; bool dfs(int u)
{
usedx[u] = ;
for(int i=; i<=ny; i++)
{
if(usedy[i] == -)
{
int t = bx[u] + by[i] - w[u][i];
if(t == )
{
usedy[i] = ;
if(cy[i] == - || dfs(cy[i]))
{
cy[i] = u;
cx[u] = i;
return ;
}
}
else if(t > )
minn = min(minn, t);
}
}
return ;
} int km()
{
mem(cx, -);
mem(cy, -);
mem(bx, -);
mem(by, );
for(int i=; i<=nx; i++)
for(int j=; j<=ny; j++)
bx[i] = max(bx[i], w[i][j]);
for(int i=; i<=nx; i++)
{
while()
{
minn = INF;
mem(usedx, -);
mem(usedy, -);
if(dfs(i)) break;
for(int j=; j<=nx; j++)
if(usedx[j] != -) bx[j] -= minn;
for(int j=; j<=ny; j++)
if(usedy[j] != -) by[j] += minn;
}
}
min_value = ;
for(int i=; i<=n; i++)
if(cx[i] != -)
min_value += w[i][cx[i]]; return min_value; } int main()
{
while(~scanf("%d",&n))
{
for(int i=; i<=n; i++)
for(int j=; j<=n; j++)
scanf("%d",&w[i][j]);
nx = ny = n;
int ans = km();
for(int i=; i<=nx; i++)
{
if(i != ) printf(" ");
printf("%d", bx[i]);
}
printf("\n");
for(int i=; i<=ny; i++)
{
if(i != ) printf(" ");
printf("%d", by[i]);
}
printf("\n");
cout<< ans <<endl; }
return ;
}
05-11 19:57