题目大意:给定一张网格图,每个人需要回到一个房子里并且一个房子只能容纳一个人,问所有人加起来的最短路径是多少;
题目解析:看到匹配,肯定是网络流了,有个坑点,题目说只要进入一个房子就不能走了,照道理有的房子是走不到的应该要bfs,然而并没有,构图简单不多说;
AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<string>
#include<queue>
#include<vector>
#include<map>
using namespace std;
const int MAXN = 110;
const int MAXM = 100000;
const int INF = 0x3fffffff;
struct Edge
{
int to,next,cap,flow,cost;
} edge[MAXM];
int head[MAXM],tol;
int pre[MAXM],dis[MAXM];
bool vis[MAXM];
int start, end;
void init()
{
tol = 0;
memset(head,-1,sizeof(head));
}
void addedge(int u,int v,int cap,int cost)
{
edge[tol].to = v;
edge[tol].cap = cap;
edge[tol].cost = cost;
edge[tol].flow = 0;
edge[tol].next = head[u];
head[u] = tol++;
edge[tol].to = u;
edge[tol].cap = 0;
edge[tol].cost = -cost;
edge[tol].flow = 0;
edge[tol].next = head[v];
head[v] = tol++;
}
bool spfa(int s,int t)
{
queue<int> q;
for(int i = 0; i < MAXM; i++)
{
dis[i] = INF;
vis[i] = false;
pre[i] = -1;
}
dis[s] = 0;
vis[s] = true;
q.push(s);
while(!q.empty())
{
int u = q.front();
q.pop();
vis[u] = false;
for(int i = head[u]; i != -1; i = edge[i].next)
{
int v = edge[i].to;
if(edge[i].cap > edge[i].flow &&
dis[v] > dis[u] + edge[i].cost )
{
dis[v] = dis[u] + edge[i].cost;
pre[v] = i;
if(!vis[v])
{
vis[v] = true;
q.push(v);
}
}
}
}
if(pre[t] == -1)
{
return false;
}
else
return true;
}
int minCostMaxflow(int s,int t,int &cost)
{
int flow = 0;
cost = 0;
while(spfa(s,t))
{
int Min = INF;
for(int i = pre[t]; i != -1; i = pre[edge[i^1].to])
{
if(Min > edge[i].cap - edge[i].flow)
Min = edge[i].cap - edge[i].flow;
}
for(int i = pre[t]; i != -1; i = pre[edge[i^1].to])
{
edge[i].flow += Min;
edge[i^1].flow -= Min;
cost += edge[i].cost * Min;
}
flow += Min;
}
return flow;
}
int n,m,nn,mm,g[MAXN][MAXN];
char graph[MAXN][MAXN];
struct point
{
int x,y;
point(int a,int b)
{
x=a;
y=b;
}
} ;
vector<point>man;
vector<point>house;
int main()
{
while(scanf("%d%d",&n,&m)!=EOF&&(n+m))
{
init();
house.clear();
man.clear();
memset(g,-1,sizeof(g));
nn=mm=0;
for(int i=1;i<=n;i++)
{
char s[110];
scanf("%s",&s[1]);
for(int j=1;j<=m;j++)
{
graph[i][j]=s[j];
if(s[j]=='.') continue;
if(s[j]=='H')
{
house.push_back(point(i,j));
nn++;
}
else
{
man.push_back(point(i,j));
mm++;
}
}
}
for(int i=0;i<mm;i++)
{
addedge(0,i+1,1,0);
}
for(int i=0;i<nn;i++)
{
addedge(mm+i+1,mm+nn+1,1,0);
}
for(int i=0;i<mm;i++)
{
for(int j=0;j<nn;j++)
{
int xx=abs(man[i].x-house[j].x);
int yy=abs(man[i].y-house[j].y);
addedge(i+1,j+1+mm,1,xx+yy);
}
}
int ans;
int f=minCostMaxflow(0,nn+mm+1,ans);
printf("%d\n",ans);
}
return 0;
}