Hdu1533 Going Home 最小费用最大流_#include
题意:用H来代表人类,m来代表房子,问每个人类到每个房子的总的 最短距离 。
思路:这里注意价值是H到M要走的距离,而容量的话,用1来表示就好了,因为H可以到达任何一个M.
剩下直接套模板就行,注意字符判断时不要带有空格。
最小费用流总结:1_尽量不要要用disk或者floyed,容易超时。2_输入时取两条边,价值取反。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int maxn = 100010;
bool vis[maxn];
int n, m, s, t, dis[maxn], pre[maxn], last[maxn], flow[maxn], maxflow, mincost;
//dis最小花费;pre每个点的前驱;last每个点的所连的前一条边;flow源点到此处的流量
struct Edge {
int to, next, flow, dis; //flow流量 dis花费
} edge[maxn];
struct node {
int x;
int y;
int w;
} H[maxn];
struct Node {
int x;
int y;
int w;
} M[maxn];
int head[maxn], num_edge = 1;
queue <int> q;
void add_edge(int from, int to, int flow, int dis) {
edge[++num_edge].next = head[from];
edge[num_edge].to = to;
edge[num_edge].flow = flow;
edge[num_edge].dis = dis;
head[from] = num_edge;
}
bool spfa(int s, int t) {
mem(dis, 0x7f);
mem(flow, 0x7f);
mem(vis, 0);
q.push(s);
vis[s] = 1;
dis[s] = 0;
pre[t] = -1;
while (!q.empty()) {
int now = q.front();
q.pop();
vis[now] = 0;
for (int i = head[now]; i != -1; i = edge[i].next) {
if (edge[i].flow > 0 && dis[edge[i].to] > dis[now] + edge[i].dis) { //正边
dis[edge[i].to] = dis[now] + edge[i].dis;
pre[edge[i].to] = now;
last[edge[i].to] = i;
flow[edge[i].to] = min(flow[now], edge[i].flow); //
if (!vis[edge[i].to]) {
vis[edge[i].to] = 1;
q.push(edge[i].to);
}
}
}
}
return pre[t] != -1;
}

void MaxFlow_MinCost() { ///最大流的最小费用
while (spfa(s, t)) {
int now = t;
maxflow += flow[t];
mincost += dis[t];
while (now != s) {
//从源点一直回溯到汇点
edge[last[now]].flow -= flow[t]; //flow和dis容易搞混
edge[last[now] ^ 1].flow += flow[t];
now = pre[now];
}
}
}

int main() {
while(cin >> n >> m,n||m){
num_edge = 1;
mincost = 0;
mem(head, -1);
num_edge = -1; //初始化
s = 0, t = 206;
char u ;
int cnt_1 = 100, cnt_2 = 0 ;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++) {
cin >> u;
if(u == 'm') {
++cnt_1;
M[cnt_1].x = i;
M[cnt_1].y = j;
} else if(u == 'H') {
++cnt_2;
H[cnt_2].x = i;
H[cnt_2].y = j;
}
}
for(int i = 1; i <= cnt_2; i++)
add_edge(s, i, 1, 0), add_edge(i, s, 0, 0);
for(int i = 101; i <= cnt_1; i++)
add_edge(i, t, 1, 0), add_edge(t, i, 0, 0);
for(int i = 1; i <= cnt_2; i++)
for(int j = 101; j <= cnt_1; j++) {
int w = abs(M[j].x - H[i].x) + abs(M[j].y - H[i].y);
add_edge(i, j, 1, w);
add_edge(j, i, 0, -w);
}
MaxFlow_MinCost();
cout << mincost << endl;
}
return 0;
}