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

时间:2023-03-09 05:01:19
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=,f=;char ch=getchar();
while(ch<''||ch>''){if(ch=='-') f=-;ch=getchar();}
while(ch>=''&&ch<=''){p=p*+ch-'';ch=getchar();}
return p*f;
}
int a[],c[];
int main()
{
int n=read();
LL sum=;
for(int i=;i<=n;i++) a[i]=read(),sum+=a[i];
sum/=n;
c[]=;
for(int i=;i<=n;i++) c[i]=c[i-]+a[i]-sum;
sort(c+,c+n+);
int mid=c[n/+];
LL ans=;
for(int i=;i<=n;i++) ans+=abs(c[i]-mid);
printf("%lld\n",ans);
return ;
}