題目大意就是讓你用KM匹配求最小權值和。
可以將所有權值都變爲相反數(正變負,負變正),然後KM模板一套得出結果,最後將結果的相反數輸出即可。
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <string.h>
#include <limits.h>
#include <string>
#include <iostream>
#include <queue>
#include <math.h>
#include <map>
#include <stack>
#include <set>
#define ms(x, n) memset(x,n,sizeof(x));
#define forn(i, n) for(int i = 0; i < (int)n; i++)
#define For(i, a, b) for(int i = (a); i <= (int)(b); i++)
#define INF 0x3f3f3f3f
#define PI acos(-1.0)
#define mod(x) (x % 10000007)
typedef long long int ll;
typedef unsigned long long int ull;
using namespace std;
#define maxn 110
int n , m, con[maxn][maxn], num_a[maxn], num_b[maxn], match[maxn], slack[maxn], book_a[maxn], book_b[maxn];
int a, b, M_cnt, H_cnt;
char mp[maxn][maxn];
struct node {
int y, x;
}M[maxn], H[maxn];
bool dfs(int x)
{
book_a[x] = 1;
for (int i = 0; i < m; ++i) {
if (book_b[i]) continue;
int gap = num_a[x] + num_b[i] - con[x][i];
if (!gap) {
book_b[i] = 1;
if (match[i] == -1 || dfs(match[i])) {
match[i] = x;
return true;
}
} else {
slack[i] = min(slack[i], gap);
}
}
return false;
}
int KM()
{
ms(match, -1); ms(num_b, 0);
for (int i = 0; i < n; ++i) {
num_a[i] = con[i][0];
for (int j = 1; j < m; ++j) {
num_a[i] = max(num_a[i], con[i][j]);
}
}
for (int i = 0; i < n; ++i) {
fill(slack, slack + n, INF);
while (1) {
ms(book_a, 0); ms(book_b, 0);
if (dfs(i)) break;
int d = INF;
for (int j = 0; j < m; ++j)
if (!book_b[j]) d = min(d, slack[j]);
for (int j = 0; j < n; ++j) {
if (book_a[j]) num_a[j] -= d;
}
for (int j = 0; j < m; ++j) {
if (book_b[j]) num_b[j] += d;
else slack[j] -= d;
}
}
}
int res = 0;
for (int i = 0; i < m; ++i) res += con[match[i]][i];
return res;
}
int main()
{
while (cin >> a >> b) {
if (a == 0 && b == 0) break;
M_cnt = H_cnt = 0;
forn(i, a) {
forn(j, b) {
cin >> mp[i][j];
if (mp[i][j] == 'm') {M[M_cnt].y = i; M[M_cnt].x = j; ++M_cnt;}
else if (mp[i][j] == 'H') {H[H_cnt].y = i; H[H_cnt].x = j; ++H_cnt;}
}
}
forn(i, M_cnt) {
forn(j, M_cnt) {
con[i][j] = -(abs(M[i].x - H[j].x) + abs(M[i].y - H[j].y));
}
}
n = M_cnt; m = H_cnt;
int ans = KM();
cout << -ans << endl;
}
return 0;
}