BZOJ 1045 糖果传递

Posted on 2016-11-07 19:49  ziliuziliu  阅读(140)  评论(0编辑  收藏  举报

奇怪的式子。最后发现取中位数。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#define maxn 1000500
using namespace std;
long long n,a[maxn],c[maxn],x1,sum[maxn],ans=0,ave;
int main()
{
    scanf("%lld",&n);
    for (long long i=1;i<=n;i++)
    {
        scanf("%lld",&a[i]);
        sum[i]=sum[i-1]+a[i];
    }
    ave=sum[n]/n;
    for (long long i=1;i<=n;i++) c[i]=(i-1)*ave-(sum[i]-sum[1]);
    sort(c+1,c+n+1);
    x1=c[n/2+1];
    for (long long i=1;i<=n;i++) ans+=abs(x1-c[i]);
    printf("%lld\n",ans);
    return 0;
}