1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
|
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <queue> #include <set> #include <vector> using namespace std;
const int INF = ~0u>>1; typedef pair <int,int> P; #define MID(x,y) ((x+y)>>1) #define iabs(x) ((x)>0?(x):-(x)) #define REP(i,a,b) for(int i=(a);i<(b);i++) #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define pb push_back #define mp make_pair #define print() cout<<"--------"<<endl #define INT_MAX 1000000000 #define maxn 150 int w[maxn][maxn],n,m; int lenx,leny; int lx[maxn],ly[maxn]; int slack[maxn]; int le[maxn]; char maps[maxn][maxn]; bool S[maxn],T[maxn];
bool match(int u){ S[u] = 1; for (int i = 1; i <= leny; i ++){ if (!T[i] && lx[u] + ly[i] == w[u][i]){ T[i] = 1; if (!le[i] || match(le[i])){ le[i] = u; return true; } }else if (slack[i] > lx[u] + ly[i] - w[u][i]){ slack[i] = lx[u] + ly[i] - w[u][i]; } } return false; }
void update(){ int d = INT_MAX; for (int j = 1; j <= leny; j ++) if (!T[j]) d = min(d,slack[j]); for (int j = 1; j <= lenx; j ++) if (S[j]) lx[j] -= d; for (int j = 1; j <= leny; j ++) if (T[j]) ly[j] += d; }
int KM(){ int ans = 0; for (int i = 1; i <= lenx; i ++) { lx[i] = -INT_MAX; for (int j = 1; j <= leny; j ++){ lx[i] = max(lx[i],w[i][j]); } } memset(ly,0,sizeof(ly)); memset(le,0,sizeof(le));
for (int i = 1;i <= lenx; i ++){ for (int j = 1; j <= leny; j ++) slack[j] = INT_MAX; while (1){ memset(S,0,sizeof(S));memset(T,0,sizeof(T)); if (match(i)) break; else update(); } }
for (int i = 1; i <= leny; i ++) if (le[i]) ans += w[le[i]][i]; return -ans; }
int main(){ while (~scanf("%d%d", &n, &m) && (n + m)){ lenx = 0,leny = 0; for (int i = 0; i < n; i ++){ scanf("%s", maps[i]); for (int j = 0; j < m; j ++){ if (maps[i][j] == 'H'){ lx[++ lenx] = i,slack[lenx] = j; }else if (maps[i][j] == 'm'){ ly[++ leny] = i,le[leny] = j; } } } for (int i = 1;i <= lenx; i ++){ for (int j = 1; j <= leny; j ++){ w[i][j] = -iabs(lx[i] - ly[j]) - iabs(slack[i] - le[j]); } }
printf("%dn",KM()); } return 0; }
|