On a grid map there are n little men and n houses. In each unit time, every little man can move one unit step, either horizontally, or vertically, to an adjacent point. For each little man, you need to pay a $1 travel fee for every step he moves, until he enters a house. The task is complicated with the restriction that each house can accommodate only one little man. 

Your task is to compute the minimum amount of money you need to pay in order to send these n little men into those n different houses. The input is a map of the scenario, a '.' means an empty space, an 'H' represents a house on that point, and am 'm' indicates there is a little man on that point. 


You can think of each point on the grid map as a quite large square, so it can hold n little men at the same time; also, it is okay if a little man steps on a grid with a house without entering that house.

Input

There are one or more test cases in the input. Each case starts with a line giving two integers N and M, where N is the number of rows of the map, and M is the number of columns. The rest of the input will be N lines describing the map. You may assume both N and M are between 2 and 100, inclusive. There will be the same number of 'H's and 'm's on the map; and there will be at most 100 houses. Input will terminate with 0 0 for N and M.

Output

For each test case, output one line with the single integer, which is the minimum amount, in dollars, you need to pay.

Sample Input

2 2
.m
H.
5 5
HH..m
.....
.....
.....
mm..H
7 8
...H....
...H....
...H....
mmmHmmmm
...H....
...H....
...H....
0 0

Sample Output

2
10
28

题意:

给出 n 行 m 列的地图,'m'表示人,'H'表示房子,'.'表示空地。一个房子只能进一个人,尽量多的人要到房子里去,人到房子的距离为花费,求最优情况下的最小花费。

裸的最小费用最大流。超级源点与人建边,流量1花费0;房子与超级汇点建边,流量1花费0;人与房子建边,流量1花费为距离。

学习:https://blog.csdn.net/lym940928/article/details/90209172

Bellman-Ford 求最小费用最大流

#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int N = 1e4 + 10;

int n, m, s, t;
int u, v, c, w;
int maxFlow, minCost;

struct node {
    int x, y;
};

struct Edge {
	int from, to, flow, cap, cost;
};

bool vis[N];
int p[N], a[N], d[N];
vector<int> g[N];
vector<Edge> edges;
vector<node>peo, house;

void init() {
    minCost = 0;
    maxFlow = 0;
	for (int i = 0; i < N; i++)
		g[i].clear();
	edges.clear();
}

void addedge(int from, int to, int cap, int cost) {
	Edge temp1 = { from, to, 0, cap, cost };
	Edge temp2 = { to, from, 0, 0, -cost };//允许反向增广
	edges.push_back(temp1);
	edges.push_back(temp2);
	int len = edges.size();
	g[from].push_back(len - 2);
	g[to].push_back(len - 1);
}

bool bellmanford(int s, int t) {
	for (int i = 0; i < N; i++)
		d[i] = inf;
	d[s] = 0;
	memset(vis, false, sizeof(vis));
	memset(p, -1, sizeof(p));
	p[s] = -1;
	a[s] = inf;
	queue<int> que;
	que.push(s);
	vis[s] = true;
	while (!que.empty()) {
		int u = que.front();
		que.pop();
		vis[u] = false;
		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]) {
					que.push(e.to);
					vis[e.to] = true;
				}
			}
		}
	}
	if (d[t] == inf)
		return false;
	maxFlow += a[t];
	minCost += d[t] * a[t];
	for (int i = t; i != s; i = edges[p[i]].from) {
		edges[p[i]].flow += a[t];
		edges[p[i] ^ 1].flow -= a[t];
	}
	return true;
}

void MCMF() {
	while (bellmanford(s, t))
		continue;
	return;
}

int main() {
    char c;
	while(~scanf("%d%d", &n, &m) && n && m) {
        peo.clear(), house.clear();
        init();
        for(int i = 1; i <= n; ++i) {
            getchar();
            for(int j = 1; j <= m; ++j) {
                cin >> c;
                if(c == 'm') peo.push_back(node{i, j});
                else if(c == 'H') house.push_back(node{i, j});
            }
        }
        int n = peo.size(), m = house.size();
        for(int i = 0; i < n; ++i)
            for(int j = 0; j < m; ++j)
                addedge(i + 1, j + n + 1, 1, abs(peo[i].x - house[j].x) + abs(peo[i].y - house[j].y));
        s = 0, t = n + m + 1;
        for(int i = 1; i <= n; ++i) addedge(s, i, 1, 0);
        for(int i = 1; i <= m; ++i) addedge(i + n, t, 1, 0);
        MCMF();
        printf("%d\n", minCost);
	}
	return 0;

}

spfa 求最小费用最大流

#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int N = 1e4 + 10;
const int M = 1e5 + 10;
struct node {
    int x, y;
};
struct Edge {
    int to, next, cap, flow, cost;
}edge[M];
int head[N], tot, pre[N], dis[N], n, m, s, t, minCost, maxFlow;
bool vis[N];
vector<node>peo, house;

void init() {
    tot = 0;
    memset(head, -1, sizeof(head));
}

void addedge(int u, int v, int cap, int cost) { //cap流量 cost花费
    edge[tot].to = v;
    edge[tot].cap = cap;
    edge[tot].cost = cost;
    edge[tot].flow = 0;
    edge[tot].next = head[u];
    head[u] = tot++;

    edge[tot].to = u;
    edge[tot].cap = 0;
    edge[tot].cost = -cost;
    edge[tot].flow = 0;
    edge[tot].next = head[v];
    head[v] = tot++;
}

bool spfa(int s, int t) {
    queue<int>q;
    for(int i = 0; i < N; ++i) {
        dis[i] = inf;
        vis[i] = 0;
        pre[i] = -1;
    }
    dis[s] = 0;
    vis[s] = 1;
    q.push(s);
    while(!q.empty()) {
        int u = q.front();
        q.pop();
        vis[u] = 0;
        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] = 1;
                    q.push(v);
                }
            }
        }
    }
    if(pre[t] == -1) return 0;
    else return 1;
}

int MCMF(int s, int t) {
    minCost = 0;
    maxFlow = 0;
    while(spfa(s, t)) {
        int minn = inf;
        for(int i = pre[t]; i != -1; i = pre[edge[i ^ 1].to]) {
            if(minn > edge[i].cap - edge[i].flow)
                minn = edge[i].cap - edge[i].flow;
        }
        for(int i = pre[t]; i != -1; i = pre[edge[i ^ 1].to]) {
            edge[i].flow += minn;
            edge[i ^ 1].flow -= minn;
            minCost += edge[i].cost * minn;
        }
        maxFlow += minn;
    }
    return maxFlow;
}

int main() {
    char c;
	while(~scanf("%d%d", &n, &m) && n && m) {
        peo.clear(), house.clear();
        init();
        for(int i = 1; i <= n; ++i) {
            getchar();
            for(int j = 1; j <= m; ++j) {
                cin >> c;
                if(c == 'm') peo.push_back(node{i, j});
                else if(c == 'H') house.push_back(node{i, j});
            }
        }
        int n = peo.size(), m = house.size();
        for(int i = 0; i < n; ++i) {
            for(int j = 0; j < m; ++j) {
                addedge(i + 1, j + n + 1, 1, abs(peo[i].x - house[j].x) + abs(peo[i].y - house[j].y));
            }
        }
        s = 0, t = n + m + 1;
        for(int i = 1; i <= n; ++i) addedge(s, i, 1, 0);
        for(int i = 1; i <= m; ++i) addedge(i + n, t, 1, 0);
        MCMF(s, t);
        printf("%d\n", minCost);
	}
	return 0;
}

dijkstra 求最小费用最大流

#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
#define P pair<int,int>
const int inf = 0x3f3f3f3f;
const int N = 1e4 + 10;
const int M = 1e5 + 10;

struct node {
    int x, y;
};
vector<node>peo, house;

struct Edge {
	int to, cap, cost, rev;
};

int n, m, s, t;
int u, v, c, w;
int maxFlow, minCost;

vector<Edge> G[N];
int h[N];   ///顶点的势
int dist[N], prevv[N], preve[N]; ///dist最短距离 prevv最短路中的父节点 preve最短路中的父边

void init() {
    maxFlow = 0;
    minCost = 0;
    for(int i = 0; i < N; ++i)
        G[i].clear();
}

void addedge(int from, int to, int cap, int cost) {
	Edge temp1 = { to, cap, cost, (int)G[to].size() };
	Edge temp2 = { from, 0, -cost, (int)G[from].size() - 1 };
	G[from].push_back(temp1);
	G[to].push_back(temp2);
}

void MCMF(int s, int t, int f, int n) {    //n是总结点数
	fill(h + 1, h + 1 + n, 0);
	while (f > 0) {
		priority_queue<P, vector<P>, greater<P> > D;
		memset(dist, inf, sizeof(dist));
		dist[s] = 0; D.push(P(0, s));
		while (!D.empty()) {
			P now = D.top(); D.pop();
			if (dist[now.second] < now.first) continue;
			int v = now.second;
			for (int i = 0; i<(int)G[v].size(); ++i) {
				Edge &e = G[v][i];
				if (e.cap > 0 && dist[e.to] > dist[v] + e.cost + h[v] - h[e.to]) {
					dist[e.to] = dist[v] + e.cost + h[v] - h[e.to];
					prevv[e.to] = v;
					preve[e.to] = i;
					D.push(P(dist[e.to], e.to));
				}
			}
		}
		if (dist[t] == inf) break;
		for (int i = 1; i <= n; ++i) h[i] += dist[i];
		int d = f;
		for (int v = t; v != s; v = prevv[v])
			d = min(d, G[prevv[v]][preve[v]].cap);
		f -= d; maxFlow += d;
		minCost += d * h[t];
		for (int v = t; v != s; v = prevv[v]) {
			Edge &e = G[prevv[v]][preve[v]];
			e.cap -= d;
			G[v][e.rev].cap += d;
		}
	}
}

int main() {
    char c;
	while(~scanf("%d%d", &n, &m) && n && m) {
        peo.clear(), house.clear();
        init();
        for(int i = 1; i <= n; ++i) {
            getchar();
            for(int j = 1; j <= m; ++j) {
                cin >> c;
                if(c == 'm') peo.push_back(node{i, j});
                else if(c == 'H') house.push_back(node{i, j});
            }
        }
        int n = peo.size(), m = house.size();
        for(int i = 0; i < n; ++i) {
            for(int j = 0; j < m; ++j) {
                addedge(i + 1, j + n + 1, 1, abs(peo[i].x - house[j].x) + abs(peo[i].y - house[j].y));
            }
        }
        s = 0, t = n + m + 1;
        for(int i = 1; i <= n; ++i) addedge(s, i, 1, 0);
        for(int i = 1; i <= m; ++i) addedge(i + n, t, 1, 0);
        MCMF(s, t, inf, n + m + 2);
        printf("%d\n", minCost);
	}
	return 0;
}