BZOJ 1045 [HAOI2008]糖果传递 ★(环形等分:中位数)

题意

有n个小朋友坐成一圈,每人有ai个糖果。每人只能给左右两人传递糖果。每人每次传递一个糖果代价为1。

思路

假设平均数是x,且a1给an了k个(k<0说明是an给a1了-k个),那么总代价就可以算出来:
an
an+ka1-ka2
代价:|k|xa1+a2-x-ka3
代价:|a1-x-k|xa1+a2+a3-2x-k
代价:|a1+a2-2x-k|x
代价:|a1+a2+a3-3x-k|
令bi=sum(a1..i)-ix,则总代价= sum|bi-k|。易知k为中位数时此值最小。问题转化为求中位数…… 用自己快速选择第K大模板TLE……sort直接过了……

代码

[cpp] #include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <string> #include <cstring> #include <vector> #include <set> #include <stack> #include <queue> #define MID(x,y) ((x+y)/2) #define MEM(a,b) memset(a,b,sizeof(a)) #define REP(i, begin, end) for (int i = begin; i <= end; i ++) using namespace std; const int maxn = 1000005; int a[maxn]; long long sum[maxn], b[maxn]; int main(){ int n; scanf("%d", &n); sum[0] = 0; REP(i, 1, n){ scanf("%d", &a[i]); sum[i] = sum[i-1] + a[i]; } long long average = sum[n] / n; REP(i, 0, n-1){ b[i] = sum[i] - (i) * average; } sort(b, b+n); long long res = 0; REP(i, 0, n-1){ res += abs(b[i] - b[n/2]); } printf("%lld\n", res); return 0; } [/cpp]

转载于:https://www.cnblogs.com/AbandonZHANG/p/4114124.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值