O(n^4)
#include <iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
const int maxn = 101;
const int INF = (1<<31)-1;
int w[maxn][maxn];
int lx[maxn],ly[maxn];
int linky[maxn];
int visx[maxn],visy[maxn];
int slack[maxn];
int nx,ny;
bool find(int x)
{
visx[x] = true;
for(int y = 0; y < ny; y++)
{
if(visy[y])
continue;
int t = lx[x] + ly[y] - w[x][y];
if(t==0)
{
visy[y] = true;
if(linky[y]==-1 || find(linky[y]))
{
linky[y] = x;
return true;
}
}
else if(slack[y] > t)
slack[y] = t;
}
return false;
}
int KM()
{
int i,j;
memset(linky,-1,sizeof(linky));
memset(ly,0,sizeof(ly));
for(i = 0; i < nx; i++)
for(j = 0,lx[i] = -INF; j < ny; j++)
if(w[i][j] > lx[i])
lx[i] = w[i][j];
for(int x = 0; x < nx; x++)
{
for(i = 0; i < ny; i++)
slack[i] = INF;
while(true)
{
memset(visx,0,sizeof(visx));
memset(visy,0,sizeof(visy));
if(find(x))
break;
int d = INF;
for(i = 0; i < ny; i++)
{
if(!visy[i] && d > slack[i])
d = slack[i];
}
for(i = 0; i < nx; i++)
{
if(visx[i])
lx[i] -= d;
}
for(i = 0; i < ny; i++)
{
if(visy[i])
ly[i] += d;
else
slack[i] -= d;
}
}
}
int result = 0;
for(i = 0; i < ny; i++)
if(linky[i]>-1)
result += w[linky[i]][i];
return result;
}
int main()
{
scanf("%d%d",&nx,&ny);
int a,b,c;
while(scanf("%d%d%d",&a,&b,&c),a+b+c)
{
w[a][b]=c;
}
printf("%d\n",KM());
break;
return 0;
}
O(n^3)
#include <cstdio>
#include <cstring>
#include <cmath>
#define INF 0x3f
#define maxn 25
using namespace std;
int nx,ny,linky[maxn];
double lack,w[maxn][maxn],lx[maxn],ly[maxn];
bool visx[maxn],visy[maxn];
bool find(int x){
visx[x]=true;
for(int i=1;i<=ny;i++){
if(visy[i]) continue;
int t=lx[x]+ly[i]-w[x][i];
if(t<0){
visy[i]=true;
if(linky[i]==-1||find(linky[i])){
linky[i]=x;
return true;
}
}else if(t<lack) lack=t;
}
return false;
}
double KM(){
memset(linky,-1,sizeof(linky));
for(int i=1;i<=ny;i++) ly[i]=0;
for(int i=1;i<=nx;i++){
lx[i]=INF;
for(int j=1;j<=ny;j++)
if(w[i][j]>lx[i]) lx[i]=w[i][j];
}
for(int x=1;x<=nx;x++){
while(true){
memset(visx,0,sizeof(visx));
memset(visy,0,sizeof(visy));
lack=INF;
if(find(x)) break;
for(int i=1;i<=ny;i++){
if(visx[i]) lx[i]-=lack;
if(visy[i]) ly[i]+=lack;
}
}
}
int ans=0;
for(int i=1;i<=ny;i++)
ans-=w[linky[i]][i];
return ans;
}