You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

31 lines
924 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
const int N = 1000010;
typedef long long LL;
LL a[N], c[N], sum, avg, n, res;
int main() {
// 加快读入
ios::sync_with_stdio(false), cin.tie(0);
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i], sum += a[i];
avg = sum / n;
// c[k]=(a[1]+a[2]+...+a[k])-k*avg
// c[k-1]=(a[1]+a[2]+...+a[k-1])-(k-1)*avg
// 努力找出c[k]与 c[k-1]之间的递推关系:
// c[k]=c[k-1]+a[k]-avg
// 所以,c数组可以通过递推得到
for (int k = 1; k <= n; k++) c[k] = c[k - 1] + a[k] - avg;
// 通过排序 => c[(n+1)/2] = 中位值
sort(c + 1, c + n + 1);
// 将x_n'放到中位值处这样几何含义上所有n 个位置上c1,c2,...cn到中位值的距离绝对值和最小
for (int i = 1; i <= n; i++) res += abs(c[i] - c[(n + 1) / 2]);
cout << res << endl;
return 0;
}