洛谷P2512 [HAOI2008]糖果传递
1 //不开long long见祖宗!!! 2 #include<bits/stdc++.h> 3 using namespace std; 4 long long n,ans,sum; 5 long long a[1000005],s[1000005]; 6 int main() 7 { 8 scanf("%lld",&n); 9 for(int i=1;i<=n;i++) {scanf("%lld",&a[i]);sum+=a[i];} 10 sum/=n; 11 for(int i=1;i<=n;i++) a[i]-=sum; 12 for(int i=1;i<=n;i++) s[i]=s[i-1]+a[i]; 13 nth_element(s+1,s+(n+1)/2,s+1+n);//STL根据第n大元素O(n)排序 14 for(int i=1;i<=n;i++) ans+=s[i]>s[(n+1)/2]?s[i]-s[(n+1)/2]:s[(n+1)/2]-s[i]; 15 printf("%lld",ans); 16 return 0; 17 }