https://acm.hdu.edu.cn/showproblem.php?pid=1533
#include
#include
#include
#include
#include
#include
using namespace std;
const int N=105,INF=0x3f3f3f3f;
typedef pair<int,int> PII;
vector ren;
vector fang;
int n,m;
int w[N][N];
int num;
int la[N],lb[N];
int va[N],vb[N];
int match[N],slash[N];
void init()
{
memset(match,0,sizeof match);
num=0;
ren.clear();
fang.clear();
}
bool dfs(int x)
{
va[x]=1;
for(int i=0;iif(vb[i]) continue;
int need=la[x]+lb[i]-w[x][i];
if(need==0)
{
vb[i]=1;
if(!match[i]||dfs(match[i]))
{
match[i]=x;
return true;
}
}
else
{
slash[i]=min(slash[i],need);
}
}
return false;
}
int km()
{
memset(lb,0,sizeof lb);
for(int i=0;ifor(int j=0;jmax(la[i],w[i][j]);
}
}
for(int i=0;imemset(slash,INF,sizeof slash);
while(1)
{
memset(va,0,sizeof va);
memset(vb,0,sizeof vb);
if(dfs(i)) break;
else
{
int d=INF;
for(int j=0;jif(!vb[j]) d=min(d,slash[j]);
}
for(int j=0;jif(va[j]) la[j]-=d;
if(vb[j]) lb[j]+=d;
}
}
}
}
int res=0;
for(int i=0;ireturn res;
}
int main(void)
{
while((cin>>n>>m)&&(n+m))
{
init();
char ch[N];
for(int i=1;i<=n;i++)
{
scanf("%s",ch+1);
for(int j=1;j<=m;j++)
{
if(ch[j]=='m')
{
ren.push_back({i,j});
num++;
}
else if(ch[j]=='H')
{
fang.push_back({i,j});
}
}
}
for(int i=0;iint a=ren[i].first,b=ren[i].second;
for(int j=0;jint c=fang[j].first,d=fang[j].second;
int x=abs(a-c),y=abs(b-d);
w[i][j]=-(x+y);
}
}
cout<<-km()<return 0;
}