[BZOJ1045] [HAOI2008] 糖果传递 (中位数)

Description

题目链接

Solution

这题跟数列的中位数有关,

具体证明见刘汝佳的蓝皮书里

Code

#include <cstdio>
#include <algorithm>
#include <cmath>
#define N 1000010 
#define ll long long
using namespace std;

int n;
ll sum,av,Ans,A[N],c[N];

inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}

int main(){
	n=read();for(int i=1;i<=n;sum+=(A[i++]=read()));
	av=sum/n;
	for(int i=1;i<n;++i) c[i]=c[i-1]+A[i]-av;
	sort(c,c+n);
	ll x1=c[n>>1];
	for(int i=0;i<n;++i) Ans+=fabs(x1-c[i]);
	printf("%lld\n",Ans);
	return 0;
}
posted @ 2018-04-13 19:29  void_f  阅读(169)  评论(0编辑  收藏  举报