裸题。。。
第一次过还是纪念下,模板还是自己写的用起来舒服些。。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <algorithm>
#include <queue>
#include <set>
using namespace std;
const int INF=0x3f3f3f3f;
const int MAXN=20000;
const int MAXM=1000005;
int n,u,v,w,s,t;
struct Edge
{
int to,next,flow,cost;
}edge[MAXM];
int head[MAXN],tot,pre[MAXN];
bool vis[MAXN];
void add(int u,int v,int w,int cost)
{
edge[tot].to=v;
edge[tot].flow=w;
edge[tot].cost=cost;
edge[tot].next=head[u];
head[u]=tot++;
edge[tot].to=u;
edge[tot].flow=0;
edge[tot].cost=-cost;
edge[tot].next=head[v];
head[v]=tot++;
}
int d[MAXN];
bool spfa()
{
int u;
for(int i=0;i<=n;++i)
{
d[i]=INF;vis[i]=false;pre[i]=-1;
}
queue <int> q;
vis[s]=true;
d[s]=0;
q.push(s);
while(!q.empty())
{
u=q.front();
q.pop();vis[u]=false;//清除在队列中的标志
for(int i=head[u];~i;i=edge[i].next)
{
int v=edge[i].to;
if(d[v]>d[u]+edge[i].cost&&edge[i].flow>0)
{
d[v]=d[u]+edge[i].cost;
pre[v]=i;
if(!vis[v])
{
vis[v]=true;//在队列中存在
q.push(v);
}
}
}
}
if(pre[t]==-1)return false;
return true;
}
int MCMF()
{
int sum=INF,ans=0;
for(int i=pre[t];~i;i=pre[edge[i^1].to])
{
sum=min(sum,edge[i].flow);
}
//可以增广时累加求出最大流 -> flow+=sum;
for(int i=pre[t];~i;i=pre[edge[i^1].to])
{
edge[i].flow-=sum;
edge[i^1].flow+=sum;
ans+=sum*edge[i].cost;//cost为单位流量费用 需乘以流量
}
return ans;
}
int go()
{
int ans=0;
while(spfa())ans+=MCMF();
return ans;
}
char mp[1005][1005];
vector < pair <int,int> > M,H;
int main()
{
//freopen("in.txt","r",stdin);
int a,b;
while(scanf("%d%d",&a,&b)==2)
{
if(a+b==0)break;
tot=0;M.clear();H.clear();
memset(head,-1,sizeof(head));
for(int i=0;i<a;++i)
{
scanf("%s",&mp[i]);
for(int j=0;j<b;++j)
{
if(mp[i][j]=='m')M.push_back(make_pair(i,j));
else if(mp[i][j]=='H')H.push_back(make_pair(i,j));
}
}
int len=M.size();
for(int i=0;i<len;++i)
{
add(1,i+2,1,0);
add(len+2+i,2*len+2,1,0);
for(int j=0;j<len;++j)
{
int x=abs(M[i].first-H[j].first)+abs(M[i].second-H[j].second);
add(i+2,len+2+j,x,x);
}
}
s=1;t=2*len+2;n=2*len+2;
printf("%d\n",go());
}
return 0;
}