题目链接:
UVALive 11383 - Golden Tiger Claw
题意:
给出一个n*n的矩阵,需要对每行和每列定义行值row[i]和列值col[j],使得对于矩阵中任意一个数值w[i][j]满足row[i] + col[j] >= w[i][j],求满足条件的行值和列值满足sigma(row[i] + col[i]) (1<=i<=n)最小.
先在一行输出所有的行值row[i],再在第二行输出所有的列值col[i],最后输出最小的sigma(row[i] + col[i]).
分析:
在KM()算法中顶标和边权的关系是lx[i] + ly[j] >= w[i][j],并且对任意i,j都满足.所以可以将所有的行看成x,所有的列看成y,那么矩阵中需要满足的关系就和KM()算法求最大权匹配时顶点需要满足的关系一样了.当算法结束后,所有顶标之和是最小的.
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;
const int MAX_N = 510;int n, m;
int matchx[MAX_N], matchy[MAX_N], visx[MAX_N], visy[MAX_N], lx[MAX_N], ly[MAX_N], w[MAX_N][MAX_N], slack[MAX_N];bool dfs(int x)
{visx[x] = 1;for(int y = 0; y < m; y++){if(visy[y] ) continue;int tmp = lx[x] + ly[y] - w[x][y];if(tmp == 0){visy[y] = 1;if(matchy[y] == -1 || dfs(matchy[y])){matchx[x] = y;matchy[y] = x;return true;}}else {slack[y] = min(slack[y], tmp);}}return false;
}void KM()
{memset(matchy, -1, sizeof(matchy));memset(ly, 0, sizeof(ly));for(int i = 0; i < n; i++){lx[i] = INT_MIN;for(int j = 0; j < m; j++){lx[i] = max(lx[i], w[i][j]);}}for(int i = 0; i < n; i++){for(int j = 0; j < m; j++) { slack[j] = INT_MAX; }while(1){memset(visx, 0, sizeof(visx));memset(visy, 0, sizeof(visy));if(dfs(i)) break;int d = INT_MAX;for(int j = 0; j < m; j++){if(!visy[j]) d = min(d, slack[j]);}//cout << "d = " << d << endl;for(int j = 0; j < n; j++) { if(visx[j]) lx[j] -= d; }for(int j = 0; j < m; j++) {if(visy[j]) ly[j] += d;else slack[j] -= d;}}}
}int main()
{freopen("O.in", "r", stdin);IOS;while(cin >> n){m = n;for(int i = 0; i < n; i++){for(int j = 0; j < n; j++){cin >> w[i][j];w[i][j] = w[i][j];}}KM();for(int i = 0; i < n; i++){if(i) cout << " ";cout << lx[i];}cout << endl;for(int i = 0; i < n; i++){if(i) cout << " ";cout << ly[i];}cout << endl;int sum = 0;for(int i = 0; i < n; i++){sum += (lx[i] + ly[i]);}cout << sum << endl;}return 0;
}