BZOJ1045: [HAOI2008]糖果传递&BZOJ1465: 糖果传递&BZOJ3293: [Cqoi2011]分金币

【传送门:BZOJ1045&BZOJ1465&BZOJ3293


简要题意:

  给出n个数,每个数每次可以-1使得左边或者右边的数+1,代价为1,求出使得这n个数相等的最小代价


题解:

  %%%hzwer


参考代码:

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long LL;
inline int read()
{
    int p=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){p=p*10+ch-'0';ch=getchar();}
    return p*f;
}
int a[1100000],c[1100000];
int main()
{
    int n=read();
    LL sum=0;
    for(int i=1;i<=n;i++) a[i]=read(),sum+=a[i];
    sum/=n;
    c[1]=0;
    for(int i=2;i<=n;i++) c[i]=c[i-1]+a[i]-sum;
    sort(c+1,c+n+1);
    int mid=c[n/2+1];
    LL ans=0;
    for(int i=1;i<=n;i++) ans+=abs(c[i]-mid);
    printf("%lld\n",ans);
    return 0;
}

 

posted @ 2018-03-27 16:30  Star_Feel  阅读(179)  评论(0编辑  收藏  举报