AcWing 122 糖果传递
很有思维难度的一道贪心题, 需要推公式,找规律,详细思路见大佬笔记:
大佬题解原地址
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int N = 1e6 + 10;
int n, m;
int a[N];
int sum, avg;
int c[N];
int main()
{
cin>>n;
for(int i = 1; i < n; i ++ ){
cin>>a[i];
sum += a[i];
}
avg = sum / n;
//c[i]是计算x[i]时所需要减去的常数
for(int i = n; i > 1; i -- ){
c[i] = c[i + 1] + avg - a[i];
}
c[1] = 0;
sort(c + 1, c + n);
int ans = 0;
for(int i = 1; i <= n; i ++ ){
ans += (c[i] - c[(i + 1) / 2]);
}
cout<<ans<<endl;
return 0;
}