有n個小朋友坐成一圈,每人有a[i]個糖果。ios
每人只能給左右兩人傳遞糖果。spa
每人每次傳遞一個糖果代價爲1。code
求使全部人得到均等糖果的最小代價。blog
第一行輸入一個正整數n,表示小朋友的個數。string
接下來n行,每行一個整數a[i],表示第i個小朋友初始獲得的糖果的顆數。it
輸出一個整數,表示最小代價。io
1≤n≤1000000
數據保證必定有解。class
4 1 2 5 4
4
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> using namespace std; typedef long long LL; const int N = 1000010; int a[N], c[N]; int n; int main() { scanf("%d", &n); for (int i = 1; i <= n; i ++) scanf("%d", &a[i]); LL sum = 0; for (int i = 1; i <= n; i ++) sum += a[i]; int avg = sum / n; for (int i = n; i > 1; i --) c[i] = c[i + 1] + avg - a[i]; c[1] = 0; sort(c + 1, c + 1 + n); int x1 = c[n / 2 + 1]; LL ans = 0; for (int i = 1; i <= n; i ++) ans += abs(c[i] - x1); printf("%lld", ans); return 0; }