poj 2195 Going Home(最小费用最大流)

时间:2023-03-08 18:16:08
poj 2195 Going Home(最小费用最大流)

题目:http://poj.org/problem?id=2195

有若干个人和若干个房子在一个给定网格中,每人走一个都要一定花费,每个房子只能容纳一人,现要求让所有人进入房子,且总花费最小。

构造一个超级源s和超级汇t,超级源s与U中所有点相连,费用cost[s][u]=0(这是显然的),容量cap[s][u]=1;V中所有点与超级汇t相连,

费用cost[v][t]=0(这是显然的),容量cap[t][v]=1。

 #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <cmath>
using namespace std;
const int INF=<<;
const int maxn=;
struct node
{
int x,y;
}p[maxn],h[maxn];
int c[maxn][maxn],f[maxn][maxn],w[maxn][maxn];
int n,m,pn,hn,s,t,ans;
bool inq[maxn]; //是否在队列中
char str[maxn][maxn];
int pre[maxn],dis[maxn];//上一条弧,Bellman_ford; void spfa()
{
int i,v;
queue<int>q;
for (i = ; i < maxn; i++)
{
dis[i] = INF;
pre[i] = -;
inq[i] = false;
}
q.push(s);
inq[s] = true;
dis[s] = ;
while (!q.empty())
{
int u = q.front();
q.pop();
inq[u] = false;
for (v = ; v <= t; v++)
{
if (c[u][v]&& dis[v] > dis[u] + w[u][v])
{
dis[v] = dis[u] + w[u][v];
pre[v] = u;
if (!inq[v])
{
q.push(v);
inq[v] = true;
}
}
}
}
}
void mcmf()
{
while ()
{
spfa();
if (pre[t] == -) break;
int x = t,minf = INF;
while (pre[x] != -)
{
minf = min(minf,c[pre[x]][x]);
x = pre[x];
}
x = t;
while (pre[x] != -)
{
c[pre[x]][x]-=minf;
c[x][pre[x]]+=minf;
ans+=minf*w[pre[x]][x];
x = pre[x];
}
}
} int main()
{
int i,j,pn,hn;
while(cin>>n>>m && n || m)
{
pn = hn = ;
memset(c,,sizeof(c));
memset(f,,sizeof(f));
memset(w,,sizeof(w));
for(i = ; i < n; i++)
{
scanf("%s",str[i]);
for(j = ; j < m; j++)
{
if(str[i][j] == 'H')
{
h[++hn].x = i;
h[hn].y = j;
}
else if(str[i][j] == 'm')
{
p[++pn].x = i;
p[pn].y = j;
}
}
}
s = ;
t = pn + hn + ;
for (i = ; i <= pn; i++)
c[s][i] = ;
for (i = ; i <= hn; i++)
c[i + pn][t] = ;
for (i = ; i <= pn; i++)
{
for (j = ; j <= hn; j++)
{
c[i][j + pn] = ;
w[i][j + pn] = abs(p[i].x - h[j].x) + abs(p[i].y - h[j].y);
w[j + pn][i] = -w[i][j + pn];
} }
ans = ;
mcmf();
printf("%d\n",ans);
}
return ;
}