KM algorithm is quite difficult to understand, that it is silent on the "top standard", there are a bunch Theorem (that do not want to see) -
but the code is still relatively good writing,
it is based on a bipartite graph maximum matching algorithm Hungary.
Look at this idea of God rush of blog it! -> | portal | <-
code optimized:
The time complexity of O (n ^ 3)
attached Code
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int inf=0x7fffffff,maxn=1010;
int w[maxn][maxn],link[maxn],lx[maxn],ly[maxn],slack[maxn];
bool visy[maxn],visx[maxn];
bool dfs(int node){
visx[node]=1;
For(i,1,m){
if(visy[i]) continue;
int ls=lx[node]+ly[i]-w[node][i];
if(ls==0){
visy[i]=1;
if(link[i]==-1 || dfs(link[i])){
link[i]=node;
return 1;
}
}
if(ls<slack[i])
slack[i]=ls;
}
return 0;
}
int km(){
int sum=0;
ak(ly);
For(i,1,n){
lx[i]=-inf;
For(j,1,n){
if(lx[i]<w[i][j])
lx[i]=w[i][j];
}
}
memset(link,-1,sizeof(link));
For(i,1,n){
For(j,1,m) slack[j]=inf;
while(1){
ak(visx),ak(visy);
if(dfs(i)) break;
int d=inf;
For(j,1,m){
if(!visy[j] && slack[j]<d)
d=slack[j];
}
For(j,1,n)
if(visx[j])
lx[j]-=d;
For(j,1,m)
if(visy[j])
ly[j]+=d;
else slack[j]-=d;
}
}
For(i,1,m){
if(link[i]>-1){
sum+=w[link[i]][i];
}
}
return sum;
}
The above blog wrote these details are resolved, not repeat them here.