首页 > 学院 > 开发设计 > 正文

网络流24题19. 负载平衡问题

2019-11-06 06:15:34
字体:
来源:转载
供稿:网友

负载平衡问题

Description

G 公司有 n 个沿铁路运输线环形排列的仓库,每个仓库存储的货物数量不等。如何用最少搬运量可以使 n 个仓库的库存数量相同。搬运货物时,只能在相邻的仓库之间搬运。 对于给定的 n 个环形排列的仓库的库存量,编程计算使 n 个仓库的库存数量相同的最少搬运量。

Input

第 1 行中有 1 个正整数 n(n<=100),表示有 n 个仓库。第 2 行中有 n 个正整数,表示 n 个仓库的库存量。

Output

输出计算出的最少搬运量。

Sample Input

5 17 9 14 16 4

Sample Output

11

题解

将每个点i拆分成xi和yi。设i点库存量ci。平均库存为ave。 建立附加源S,附加汇T。 建图: 1.S向xi连接一条容量为ci费用为0的边。 2.yi向T连接一条容量为ave费用为0的边。 3.xi向yi连接一条容量为inf费用为0的边,yi向xi连接一条容量为inf费用为0的边。 4.设i相邻点为j,xi向yj连接一条容量为inf,费用为1的边。 最小费用就是答案。

#include<cstdio>#include<iostream>#include<cstring>using namespace std;const int N = 1000 + 10, M = 1000000 + 10, inf = 0x3f3f3f3f;struct Edge{ int fr, to, cap, flow, cost;}edg[M];int hd[N], nxt[M], tot;int n, s, t;int d[N], a[N], p[N], q[N], inq[N];int wt[N], ave, cl[N];void insert(int u, int v, int w, int x){ edg[tot].fr = u, edg[tot].to = v, edg[tot].cap = w, edg[tot].flow = 0, edg[tot].cost = x; nxt[tot] = hd[u]; hd[u] = tot; tot++; edg[tot].fr = v, edg[tot].to = u, edg[tot].cap = 0, edg[tot].flow = 0, edg[tot].cost = -x; nxt[tot] = hd[v]; hd[v] = tot; tot++;}bool spfa(int &fl, int &cst){ for(int i = s; i <= t; i++) d[i] = inf; d[s] = 0; p[s] = 0; a[s] = inf; int head = 0, tail = 1; q[0] = s; inq[s] = 1; while(head != tail){ int u = q[head++]; if(head == 1001) head = 0; inq[u] = 0; for(int i = hd[u]; i >= 0; i = nxt[i]){ Edge &e = edg[i]; if(d[e.to] > d[u] + e.cost && e.cap > e.flow){ d[e.to] = d[u] + e.cost; p[e.to] = i; a[e.to] = min(a[u], e.cap - e.flow); if(!inq[e.to]){ q[tail++] = e.to; if(tail == 1001) tail = 0; inq[e.to] = 1; } } } } if(d[t] == inf) return false; fl += a[t]; cst += a[t] * d[t]; int u = t; while(u != s){ edg[p[u]].flow += a[t]; edg[p[u]^1].flow -= a[t]; u = edg[p[u]].fr; } return true;}void init(){ scanf("%d", &n); for(int i = 1; i <= n; i++){ scanf("%d", &wt[i]); ave += wt[i]; } ave /= n; for(int i = 1; i <= n; i++) cl[i] = wt[i] - ave;}void build(){ memset(hd, -1, sizeof(hd)); s = 0, t = n * 2 + 1; for(int i = 1; i <= n; i++){ insert(s, i, wt[i], 0); insert(n + i, t, ave, 0); insert(i, n + i, inf, 0); insert(n + i, i, inf, 0); int j = i - 1; if(j < 1) j += n; insert(i, n + j, inf, 1); j = i + 1; if(j > n) j -= n; insert(i, n + j, inf, 1); }}void work(){ build(); int flow = 0, cost = 0; while(spfa(flow, cost)); PRintf("%d/n", cost);}int main(){ freopen("prog819.in", "r", stdin); freopen("prog819.out", "w", stdout); init(); work(); return 0;}
上一篇:4.最近距离

下一篇:http协议学习系列

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表