中位数思想,证明详见:
http://blog.csdn.net/zhengnanlee/article/details/8915098
注意是对谁排序,要搞清楚金钱的来源和去向- -
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define mytype long long int
mytype b[1000010];
int main()
{
//ios::sync_with_stdio(false);//禁用同步,加速
int n;
while(cin>>n)
{
int t = n;
vector<mytype> a;
mytype sum = 0;
while(t--)
{
mytype temp;
cin>>temp;
a.push_back(temp);
sum += temp;
}
mytype M = sum / n;
b[0]=0;
for(int i=1; i < n; i++)
{
b[i] = b[i-1] + M - a[i];
}
sort(b,b+n);
mytype x1 = b[n/2];
mytype ans = 0;
for(int i=0; i < n; i++)
{
ans += abs( x1 - b[i] );
}
cout<<ans<<endl;
}
}