http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=33899
思路:推公式,发现可以转化为求给定n个数,求到所有点距离之和最小的点的问题
#include <iostream> #include <algorithm> #include <cstdio> #include <cmath> #define RPE(i,n) for(int i=1;i<=(n);i++) typedef long long LL; const int maxn=1e6+10; LL a[maxn],c[maxn]; using namespace std; int main() { ios::sync_with_stdio(false); int n,ca=1; while(cin>>n) { LL sum=0; RPE(i,n) { cin>>a[i]; sum+=a[i]; } LL m=sum/n; c[1]=0; RPE(i,n) { c[i]=c[i-1]-(a[i]-m); } sort(c+1,c+n+1); LL ans=0; RPE(i,n) ans+=abs(c[i]-c[n/2]); cout<<ans<<endl; } return 0; }