题目链接
题意:
给一个n*n的矩阵,每个格子中有正整数w[i][j],试为每行和每列分别确定一个数字row[i]和col[i],使得任意格子w[i][j]<=row[i]+col[j]恒成立。先输row,再输出col,再输出全部总和(总和应尽量小)。
解题报告:这道题中w[i][j]<=row[i]+col[j]满足KM算法中顶标的性质,所以可以用KM算法,算法结束时的顶标值就是答案。
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 505;int w[N][N], n, Lx[N], Ly[N], slack[N], line[N];
bool S[N], T[N];bool find(int i){S[i]=1;for ( int j=1; j<=n; j++ ){if( !T[j] ){if( Lx[i]+Ly[j]==w[i][j] ){T[j]=1;if( line[j]==-1 || find(line[j]) ){line[j]=i;return true;}}else slack[j]=min(slack[j],Lx[i]+Ly[j]-w[i][j]);}}return false;
}
#define Inf 0x3f3f3f3fint KM(){memset(line, -1, sizeof(line));memset(Ly,0,sizeof(Ly));for ( int i=1; i<=n; i++ ){Lx[i]=-Inf;for ( int j=1; j<=n; j++ )if( Lx[i]<w[i][j] ) Lx[i]=w[i][j];}for ( int i=1; i<=n; i++ ){for ( int j=1; j<=n; j++ ) slack[j]=Inf;while( true ){memset(S,false,sizeof(S));memset(T,false,sizeof(T));if( find(i) ) break;int d=Inf;for ( int j=1; j<=n; j++ ) if( !T[j] && d>slack[j]) d=slack[j];for ( int j=1; j<=n; j++ ){if( S[j] ) Lx[j]-=d;} for ( int j=1; j<=n; j++ ){if( T[j] ) Ly[j]+=d;else slack[j]-=d;}}}for ( int i=1; i<=n; i++ ) printf("%d ", Lx[i] );printf("\n");for ( int i=1; i<=n; i++ ) printf("%d ", Ly[i] );int ans=0;for ( int i=1; i<=n; i++ )ans+=Lx[i]+Ly[i];return ans;
}
int main(){while( ~scanf("%d", &n ) ){for ( int i=1; i<=n; i++ )for ( int j=1; j<=n; j++ )scanf("%d", &w[i][j] );printf("\n%d\n", KM() );}
}