2 2 .m H. 5 5 HH..m ..... ..... ..... mm..H 7 8 ...H.... ...H.... ...H.... mmmHmmmm ...H.... ...H.... ...H.... 0 0
2 10 28
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 #define pii pair<int,int> 6 #define INF 0x3f3f3f3f 7 using namespace std; 8 const int maxn = 200; 9 struct arc { 10 int to,flow,cost,next; 11 arc(int x = 0,int y = 0,int z = 0,int nxt = -1) { 12 to = x; 13 flow = y; 14 cost = z; 15 next = nxt; 16 } 17 } e[maxn*maxn]; 18 int head[maxn*10],d[maxn*10],p[maxn*10],n,m; 19 char mp[maxn][maxn]; 20 bool in[maxn*10]; 21 int hs[maxn][maxn],pid,hid,S,T,tot; 22 void add(int u,int v,int flow,int cost) { 23 e[tot] = arc(v,flow,cost,head[u]); 24 head[u] = tot++; 25 e[tot] = arc(u,0,-cost,head[v]); 26 head[v] = tot++; 27 } 28 bool isIn(int x,int y) { 29 return x >= 0 && x < n && y >= 0 && y < m; 30 } 31 void bfs(int x,int y) { 32 queue< pii >q; 33 q.push(make_pair(x,y)); 34 int ds[maxn][maxn]; 35 memset(ds,-1,sizeof(ds)); 36 ds[x][y] = 0; 37 static const int dir[4][2] = {-1,0,1,0,0,-1,0,1}; 38 while(!q.empty()) { 39 pii now = q.front(); 40 q.pop(); 41 for(int i = 0; i < 4; ++i) { 42 int tx = now.first + dir[i][0]; 43 int ty = now.second + dir[i][1]; 44 if(isIn(tx,ty) && ds[tx][ty] == -1) { 45 ds[tx][ty] = ds[now.first][now.second] + 1; 46 q.push(make_pair(tx,ty)); 47 if(mp[tx][ty] == 'H') 48 add(hs[x][y],pid+hs[tx][ty],1,ds[tx][ty]); 49 } 50 } 51 } 52 } 53 bool spfa() { 54 queue<int>q; 55 for(int i = 0; i <= T; ++i) { 56 d[i] = INF; 57 in[i] = false; 58 p[i] = -1; 59 } 60 d[S] = 0; 61 q.push(S); 62 while(!q.empty()) { 63 int u = q.front(); 64 q.pop(); 65 in[u] = false; 66 for(int i = head[u]; ~i; i = e[i].next) { 67 if(e[i].flow && d[e[i].to] > d[u] + e[i].cost) { 68 d[e[i].to] = d[u] + e[i].cost; 69 p[e[i].to] = i; 70 if(!in[e[i].to]) { 71 in[e[i].to] = true; 72 q.push(e[i].to); 73 } 74 } 75 } 76 } 77 return p[T] > -1; 78 } 79 80 int solve() { 81 int ans = 0; 82 while(spfa()) { 83 int minF = INF; 84 for(int i = p[T]; ~i; i = p[e[i^1].to]) 85 minF = min(minF,e[i].flow); 86 for(int i = p[T]; ~i; i = p[e[i^1].to]) { 87 e[i].flow -= minF; 88 e[i^1].flow += minF; 89 } 90 ans += d[T]*minF; 91 } 92 return ans; 93 } 94 int main() { 95 while(scanf("%d %d",&n,&m),n||m) { 96 memset(head,-1,sizeof(head)); 97 hid = pid = 0; 98 for(int i = tot = 0; i < n; ++i) { 99 scanf("%s",mp[i]); 100 for(int j = 0; j < m; ++j) 101 if(mp[i][j] == 'H') hs[i][j] = hid++; 102 else if(mp[i][j] == 'm') hs[i][j] = pid++; 103 } 104 S = hid + pid; 105 T = S + 1; 106 for(int i = 0; i < n; ++i) 107 for(int j = 0; j < m; ++j) 108 if(mp[i][j] == 'm') { 109 bfs(i,j); 110 add(S,hs[i][j],1,0); 111 } else if(mp[i][j] == 'H') add(hs[i][j]+pid,T,1,0); 112 printf("%d\n",solve()); 113 } 114 return 0; 115 }