题意:给你一幅图,里面得m代表人,H代表房子,问所有人都到达房子需要花多少步。
题解:看到这个题我立刻想起了POJ3057,不过这个题没有时间,只是求花多少步。相较之下简单一点,那就可以对每个人来说,对每个房子建一条容量为1,花费为距离的边,然后超级源点S到每个人建容量为1花费为0的边,每个房子对超级汇点建容量为1花费为0的边,跑一边费用流就好了。
#include<bits/stdc++.h>
using namespace std;
const int MAXN = 10000;
const int MAXM = 100000;
const int INF = 0x3f3f3f3f;
struct Edge
{
int to,next,cap,flow,cost;
} edge[MAXM];
int head[MAXN],tol;
int pre[MAXN],dis[MAXN];
bool vis[MAXN];
int N;//节点总个数,节点编号从0~N-1
void init(int n)
{
N = n;
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 < N; 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;
}
//返回的是最大流,cost存的是最小费用
//返回的是最大流,cost存的是最小费用
void 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;
}
char s[105][105];
vector<int> px,py;
vector<int> dx,dy;
int abs(int a)
{
return a>0?a:-a;
}
int main()
{
int n,m;
while(scanf("%d %d",&n,&m)&& (n+m))
{
memset(s,0,sizeof s);
px.clear();
py.clear();
dx.clear();
dy.clear();
for (int i = 0; i < n; i++)
{
scanf("%s",s[i]);
}
for (int i = 0; i < n ; i++)
{
for(int j = 0; j < m ; j++)
{
if(s[i][j] == 'm')
{
dx.push_back(i);
dy.push_back(j);
}
else if(s[i][j] == 'H')
{
px.push_back(i);
py.push_back(j);
}
}
}
int nd = dx.size(),np = px.size();
init(nd + np + 2);
for (int i = 0; i < nd; i++)
{
int x = dx[i], y = dy[i];
for (int j = 0; j < np; j++)
{
int xx = px[j], yy = py[j];
int dis = abs(x - xx) + abs(y - yy);
addedge(i + 1, j + nd + 1, 1, dis);
}
addedge(0, i + 1, 1, 0);
}
for (int i = 0; i < np; i++)
{
addedge(i + nd + 1, nd + np + 1,1, 0);
}
int cost ;
minCostMaxflow(0,nd + np + 1,cost);
printf("%d\n",cost);
}
}