poj2195
/*
POJ 2195 Going Home
邻接表形式最小费用最大流
*/
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
const int MAXN=1000;
const int MAXE=100000;
const int INF=0x3f3f3f3f;
struct Edge
{
int from;
int to;
int next;
int re;//记录逆边的下标
int cap;//容量
int cost;//费用
}edge[MAXE];
int pre[MAXN];
int head[MAXN];
bool vis[MAXN];
int que[MAXN];
int dist[MAXN];
int tol;//边的总数
void add(int u,int v,int ca,int co)
{
edge[tol].from=u;
edge[tol].to=v;
edge[tol].cap=ca;
edge[tol].cost=co;
edge[tol].re=tol+1;
edge[tol].next=head[u];
head[u]=tol++;
edge[tol].from=v;//加逆边
edge[tol].to=u;
edge[tol].cap=0;
edge[tol].cost=-co;
edge[tol].re=tol-1;
edge[tol].next=head[v];
head[v]=tol++;
}
int n;
int start;
int end;
bool SPFA()
{
int front=0,rear=0;
for(int v=0;v<=n;v++)
{
if(v==start)
{
que[rear++]=v;
vis[v]=true;
dist[v]=0;
}
else
{
dist[v]=INF;
vis[v]=false;
}
}
while(front!=rear)
{
int u=que[front++];
vis[u]=false;
if(front>=MAXN)front=0;
for(int i=head[u];i!=-1;i=edge[i].next)
{
int v=edge[i].to;
if(edge[i].cap&&dist[v]>dist[u]+edge[i].cost)
{
dist[v]=dist[u]+edge[i].cost;
pre[v]=i;
if(!vis[v])
{
que[rear++]=v;
vis[v]=true;
if(rear>=MAXN)rear=0;
}
}
}
}
if(dist[end]==INF)return false;
return true;
}
int c;//费用
int f;//最大流
void minCostMaxflow()
{
c=f=0;
int u,p;
while(SPFA())
{
int Min=INF;
for(u=end;u!=start;u=edge[p].from)
{
p=pre[u];
Min=min(Min,edge[p].cap);
}
for(u=end;u!=start;u=edge[p].from)
{
p=pre[u];
edge[p].cap-=Min;
edge[edge[p].re].cap+=Min;
}
c+=dist[end]*Min;
f+=Min;
}
}
struct Node
{
int x,y;
};
Node node1[MAXN],node2[MAXN];
char str[MAXN][MAXN];
int main()
{
// freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
int N,M;
while(scanf("%d%d",&N,&M))
{
if(N==0&&M==0)break;
int tol1=0,tol2=0;
for(int i=0;i<N;i++)
{
scanf("%s",&str[i]);
for(int j=0;j<M;j++)
{
if(str[i][j]=='m')
{
tol1++;
node1[tol1].x=i;
node1[tol1].y=j;
}
else if(str[i][j]=='H')
{
tol2++;
node2[tol2].x=i;
node2[tol2].y=j;
}
}
}
start=0;
n=tol1+tol2+1;
end=tol1+tol2+1;
//加边之前一定要初始化
tol=0;//边数
memset(head,-1,sizeof(head));//一定要初始化为-1
for(int i=1;i<=tol1;i++)
{
add(0,i,1,0);
}
for(int i=1;i<=tol2;i++)
{
add(tol1+i,end,1,0);
}
for(int i=1;i<=tol1;i++)
for(int j=1;j<=tol2;j++)
{
int temp=abs(node1[i].x-node2[j].x)+abs(node1[i].y-node2[j].y);
add(i,tol1+j,1,temp);
}
minCostMaxflow();
printf("%d\n",c);
}
return 0;
}