这个题有一些数学思维在里面,记住x[i]表示a[i+1]给a[i]拿的个数, 然后推公式
代码:
#include<iostream> #include<cmath> #include<algorithm> using namespace std; #define ll long long const int maxn=1e6+10; ll a[maxn],sum, aa, ans; int n; int main() { cin>>n; for (int i=1;i<=n;i++) {cin>>a[i];sum+=a[i];} sum/=n; a[1]=sum-a[1]; for (int i=2;i<=n;i++){ aa=sum-a[i]; a[i]=a[i-1]+aa; } sort(a+1,a+n+1); aa=a[n/2+1]; for (int i=1;i<=n;i++) ans+=abs(aa-a[i]); cout<<ans<<endl; }