'commit'
This commit is contained in:
30
TangDou/AcWing_TiGao/T6/PaiXu/122.cpp
Normal file
30
TangDou/AcWing_TiGao/T6/PaiXu/122.cpp
Normal file
@@ -0,0 +1,30 @@
|
||||
#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;
|
||||
}
|
||||
Reference in New Issue
Block a user