题目描述
有n<=1e6n<=1e6n<=1e6个小朋友坐成一圈,每人有ai个糖果。每人只能给左右两人传递糖果。每人每次传递一个糖果代价为1。求使所有人获得均等糖果的最小代价。
三倍经验:UVA11300 HAOI2008 负载平衡问题
糖果的数量是一定的,平均值能算出来,我们只要知道其中任何两个人之间的传递就能推出所有人。
做个前缀和然后排序取中位数就可以了。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <cstring>
#include <queue>
#include <cmath>
#include <map>
#include <set>
using namespace std;
#define REP(i, a, b) for(int i = a; i <= b; i++)
#define PER(i, a, b) for(int i = a; i >= b; i--)
#define LL long long
inline int read() {
int x = 0, flag = 1;char ch = getchar();
while(!isdigit(ch)) {
if(ch == '-') flag = - 1;
ch = getchar();
}
while(isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
return x * flag;
}
const int N = 2e6 + 6;
int n, a[N], c[N], M;
LL ans, tot;
int main() {
while(scanf("%d", &n) != EOF) {
tot = 0;
REP(i, 1, n) a[i] = read(), tot += a[i];
M = tot / n;
REP(i, 1, n - 1) c[i] = c[i - 1] + a[i] - M;
sort(c, c + n); tot = c[n / 2];
REP(i, 0, n - 1) ans = ans + abs(tot - c[i]);
printf("%lld\n", ans);
}
return 0;
}