思路
对于每两个相邻仓库 都建立一条容量为无穷大 费用为1的边
对于每个仓库
如果有仓库货物数量小于平均值的 则将其连向汇点 边的容量为与平均值的差
如果有大于平均值的 又源点连一条边容量也为与平均值的差
从而可以达到把所有多余货物从所有多于平均值的仓库流到所有低于平均值的仓库且是由图的内部各仓库之间的流动来完成的
代码
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
const int N = 110, M = 1010, INF = 1e8;
int n, S, T;
int h[N], e[M], ne[M], f[M], w[M], idx;
int d[N], pre[N], incf[N];
bool st[N];
int s[N];
queue<int> q;
void add(int a, int b, int c, int d)
{
e[idx] = b, ne[idx] = h[a], f[idx] = c, w[idx] = d, h[a] = idx ++ ;
e[idx] = a, ne[idx] = h[b], f[idx] = 0, w[idx] = -d, h[b] = idx ++ ;
}
bool spfa()
{
memset(d, 0x3f, sizeof d);
memset(incf, 0, sizeof incf);
q.push(S), incf[S] = INF, d[S] = 0;
while (q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for (int i = h[t]; ~i; i = ne[i])
{
int ver = e[i];
if (f[i] && d[ver] > d[t] + w[i])
{
d[ver] = d[t] + w[i];
pre[ver] = i;
incf[ver] = min(f[i], incf[t]);
if (!st[ver])
{
q.push(ver);
st[ver] = true;
}
}
}
}
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()
{
scanf("%d", &n);
S = 0, T = n + 1;
memset(h, -1, sizeof h);
int tot = 0;
for (int i = 1; i <= n; i ++ )
{
scanf("%d", &s[i]);
tot += s[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 (tot > s[i]) add(i, T, tot - s[i], 0);
else if (tot < s[i]) add(S, i, s[i] - tot, 0);
}
printf("%d\n", EK());
return 0;
}