标签:
题目大意:在一张地图上,有n个人和n间房间,现在要求将这n个人移动到这n间房子里面,移动一次的代价是1,每间房子最终只能属于1个人,问最少的移动代价是多少
解题思路:
超级源点–人,容量为1,费用为0
人—房子,容量为1,费用为移动距离
房子—超级汇点,容量为1,费用为0
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
#define N 1010
#define INF 0x3f3f3f3f
struct Edge{
int from, to, cap, flow ,cost;
Edge() {}
Edge(int from, int to, int cap, int flow, int cost):from(from), to(to), cap(cap), flow(flow), cost(cost) {}
};
struct MCMF{
int n, m, source, sink;
vector<Edge> edges;
vector<int> G[N];
int d[N], f[N], p[N];
bool vis[N];
void init(int n) {
this->n = n;
for (int i = 0; i <= n; i++)
G[i].clear();
edges.clear();
}
void AddEdge(int from, int to, int cap, int cost) {
edges.push_back(Edge(from, to, cap, 0, cost));
edges.push_back(Edge(to, from, 0, 0, -cost));
m = edges.size();
G[from].push_back(m - 2);
G[to].push_back(m - 1);
}
bool BellmanFord(int s, int t, int &flow, int &cost) {
for (int i = 0; i <= n; i++)
d[i] = INF;
memset(vis, 0, sizeof(vis));
vis[s] = 1; d[s] = 0; f[s] = INF; p[s] = 0;
queue<int> Q;
Q.push(s);
while (!Q.empty()) {
int u = Q.front();
Q.pop();
vis[u] = 0;
for (int i = 0; i < G[u].size(); i++) {
Edge &e = edges[G[u][i]];
if (e.cap > e.flow && d[e.to] > d[u] + e.cost) {
d[e.to] = d[u] + e.cost;
p[e.to] = G[u][i];
f[e.to] = min(f[u], e.cap - e.flow);
if (!vis[e.to]) {
vis[e.to] = true;
Q.push(e.to);
}
}
}
}
if (d[t] == INF)
return false;
flow += f[t];
cost += d[t];
int u = t;
while (u != s) {
edges[p[u]].flow += f[t];
edges[p[u] ^ 1].flow -= f[t];
u = edges[p[u]].from;
}
return true;
}
int Mincost(int s, int t) {
int flow = 0, cost = 0;
while (BellmanFord(s, t, flow, cost));
return cost;
}
};
//超级源点 -- 人 容量为1,费用为0
//人---房子,容量为1,费用为移动距离
//房子--超级汇点,容量为1,费用为0
MCMF mcmf;
#define M 110
#define ABS(x) ((x) > 0 ? x : (-(x)))
struct Man{
int x, y;
}man[M];
struct House{
int x, y;
}house[M];
char map[M][M];
int n, m;
void solve() {
for (int i = 0; i < n; i++)
scanf("%s", map[i]);
int cnt_m = 0, cnt_h = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) {
if (map[i][j] == ‘m‘) {
man[cnt_m].x = i;
man[cnt_m++].y = j;
}
else if(map[i][j] == ‘H‘) {
house[cnt_h].x = i;
house[cnt_h++].y = j;
}
}
if (cnt_m + cnt_h == 0) {
printf("0\n");
return ;
}
int s = cnt_m + cnt_h, t = cnt_m + cnt_h + 1;
mcmf.init(t);
for (int i = 0; i < cnt_m; i++)
mcmf.AddEdge(s, i, 1, 0);
for (int i = 0; i < cnt_h; i++)
mcmf.AddEdge(cnt_m + i, t, 1, 0);
for (int i = 0; i < cnt_m; i++) {
for (int j = 0; j < cnt_h; j++) {
int x = ABS(man[i].x - house[j].x);
int y = ABS(man[i].y - house[j].y);
mcmf.AddEdge(i, cnt_m + j, 1, x + y);
}
}
printf("%d\n", mcmf.Mincost(s, t));
}
int main() {
while (scanf("%d%d", &n, &m) != EOF && n + m) {
solve();
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/l123012013048/article/details/47257133