活动 - AcWing
G 公司有 n 个沿铁路运输线环形排列的仓库,每个仓库存储的货物数量不等。
如何用最少搬运量可以使 n 个仓库的库存数量相同。
搬运货物时,只能在相邻的仓库之间搬运。
数据保证一定有解。
输入格式
第 1 行中有 1 个正整数 n,表示有 n 个仓库。
第 2 行中有 n 个正整数,表示 n 个仓库的库存量。
输出格式
输出最少搬运量。
数据范围
1≤n≤100
每个仓库的库存量不超过 100
输入样例:
5
17 9 14 16 4
输出样例:
11
解析:
我们可以计算出最终每个仓库的货物数量 x,设第 i 个仓库的货物数量是 ai,那么所有货物一定会分成两类,一类是 ai>x,即一定会从这些仓库中流出货物,另一类是 ai<x,即一定会有货物流入这些仓库。
因此我们可以根据这两类,将所有 ai>x 的仓库作为左部节点,所有 ai<x 的仓库作为右部节点。从源点向所有左部节点连边,容量就是左部节点最开始多出来的货物,即 ai−x,费用就是 0,因为最开始货物就在左部节点中。从所有右部节点向汇点连边,容量就是右部节点缺少的货物,即 x−ai,费用也是 0,因为最终货物到右部节点就停止了。然后从每个仓库向相邻两个仓库连边,容量是 +∞,费用是 1,表示一次搬运量。
然后还需要证明对应关系,对于任意一个原问题的情况,从源点流进仓库的流量等于流出的流量(根据上述新图的定义),满足流量守恒;又因为根据上述新图的定义,易知边一定满足容量限制,所以原问题的方案对应一个最大流。同时,更具上述的建的新图,易知流量产生的费用对应一个问题的方案。因此,原问题和新图的最大流是一一对应的,且数值上相等。
并且可以发现原问题的搬运量就对应的流网络的可行流的费用,因此最小搬运量就对应了最小费用最大流,用 EK 算法来求即可
#include<iostream>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>
#include<sstream>
#include<deque>
#include<unordered_map>
#include<unordered_set>
#include<bitset>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int, int> PII;
const int N = 100 + 10, M = (100*2+100) * 2 + 10, INF = 0x3f3f3f3f;
int n, m, S, T;
int h[N], e[M], f[M],w[M], ne[M],idx;
int q[N], d[N], pre[N], incf[N];
bool st[N];
int p[N];void add(int a, int b, int c,int d) {e[idx] = b, f[idx] = c, w[idx] = d, ne[idx] = h[a], h[a] = idx++;e[idx] = a, f[idx] = 0, w[idx] = -d, ne[idx] = h[b], h[b] = idx++;
}bool spfa() {int hh = 0, tt = 1;memset(d, 0x3f, sizeof d);memset(incf, 0, sizeof incf);q[0] = S, d[S] = 0, incf[S] = 0x3f;while (hh != tt) {int t = q[hh++];if (hh == N)hh = 0;st[t] = 0;for (int i = h[t]; i != -1; i = ne[i]) {int j = e[i];if (f[i] && d[j] > d[t] + w[i]) {d[j] = d[t] + w[i];pre[j] = i;incf[j] = min(incf[t], f[i]);if (!st[j]) {q[tt++] = j;if (tt == N)tt = 0;st[j] = 1;}}}}return incf[T] > 0;
}int EK() {int cost = 0;while (spfa()) {int t = incf[T];cost += t * d[T];for (int i = T; i != S; i = e[pre[i] ^ 1]) {f[pre[i]] -= t;f[pre[i] ^ 1] += t;}}return cost;
}int main() {cin >> n;memset(h, -1, sizeof h);S = 0, T = n + 1;int tot = 0;for (int i = 1,a; i <= n; i++) {scanf("%d", &p[i]);tot += p[i];add(i, i < n ? i + 1 : 1, INF, 1);add(i, i > 1 ? i - 1 : n, INF, 1);}tot /= n;for (int i = 1; i <= n; i++) {if (p[i] > tot)add(S, i, p[i] - tot, 0);else if(tot>p[i])add(i, T, tot - p[i], 0);}printf("%d\n", EK());return 0;
}