题意:
给定一个N*M的地图,地图上有若干个man和house,且man与house的数量一致。man每移动一格需花费$1(即单位费用=单位距离),一间house只能入住一个man。现在要求所有的man都入住house,求最小费用。
分析:
二分图的最大匹配
我采用的是最小费用最大流算法,重点在建图。
Code:
#include <cmath>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn = 200 + 10;
const int INF = 1000000000;
typedef long long LL;
int msum, hsum;
struct xy {
int x, y;
xy(int x = 0, int y = 0): x(x), y(y) {}
};
xy M[maxn], H[maxn];
struct Edge {
int from, to, cap, flow, cost;
};
struct MCMF {
int n, m, s, t;
vector<Edge> edges;
vector<int> G[maxn];
int vis[maxn];
int d[maxn];
int p[maxn];
int a[maxn];
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& cost) {
for (int i = 0; i <= n; i++) d[i] = INF;
memset(vis, 0, sizeof(vis));
d[s] = 0; vis[s] = 1; p[s] = 0; a[s] = INF;
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];
a[e.to] = min(a[u], e.cap - e.flow);
if (!vis[e.to]) { Q.push(e.to); vis[e.to] = 1;}
}
}
}
if (d[t] == INF) return false;
cost += d[t] * a[t];
int u = t;
while (u != s) {
edges[p[u]].flow += a[t];
edges[p[u] ^ 1].flow -= a[t];
u = edges[p[u]].from;
}
return true;
}
int Mincost(int s, int t) {
int cost = 0;
while (BellmanFord(s, t, cost));
return cost;
}
};
MCMF g;
int n, m, s, t;
int dis(xy& a, xy& b) {
return abs(a.x - b.x) + abs(a.y - b.y);
}
void make_graph() {
int i, j, cost;
char str[maxn];
msum = hsum = 0;
for (i = 0; i < n; i++) {
scanf("%s", str);
for (j = 0; j < m; j++)
if (str[j] == 'm') {
M[msum++] = xy(i, j);
} else if (str[j] == 'H') {
H[hsum++] = xy(i, j);
}
}
s = msum + hsum + 1, t = msum + hsum + 2;
g.init(t);
for (i = 0; i < msum; i++)
for (j = 0; j < hsum; j++) {
cost = dis(M[i], H[j]);
g.AddEdge(i, j + msum, 1, cost);
}
for (i = 0; i < msum; i++) g.AddEdge(s, i , 1, 0);
for (i = 0; i < hsum; i++) g.AddEdge(i + msum, t, 1, 0);
};
int main() {
while (scanf("%d%d", &n, &m)) {
if (n == 0 && m == 0) break;
make_graph();
int answer = g.Mincost(s, t);
printf("%d\n", answer);
}
return 0;
}