Files
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

31 lines
924 B
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}