传递糖果问题

探讨了在有限数量的小朋友中,通过最少的糖果传递次数实现糖果均等分配的问题。利用前缀和与排序中位数的方法,解决了UVA11300HAOI2008的负载平衡挑战。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

n&lt;=1e6n&lt;=1e6n<=1e6个小朋友坐成一圈,每人有ai个糖果。每人只能给左右两人传递糖果。每人每次传递一个糖果代价为1。求使所有人获得均等糖果的最小代价。
三倍经验:UVA11300 HAOI2008 负载平衡问题

糖果的数量是一定的,平均值能算出来,我们只要知道其中任何两个人之间的传递就能推出所有人。
做个前缀和然后排序取中位数就可以了。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <vector>
#include <cstring>
#include <queue>
#include <cmath>
#include <map>
#include <set>
using namespace std;
#define REP(i, a, b) for(int i = a; i <= b; i++)
#define PER(i, a, b) for(int i = a; i >= b; i--)
#define LL long long
inline int read() {
    int x = 0, flag = 1;char ch = getchar();
    while(!isdigit(ch)) {
        if(ch == '-') flag = - 1;
        ch = getchar();
    }
    while(isdigit(ch)) x = x * 10 + ch - '0', ch = getchar();
    return x * flag;
}

const int N = 2e6 + 6;
int n, a[N], c[N], M;
LL ans, tot;
 
int main() {   
    while(scanf("%d", &n) != EOF) {
        tot = 0;
        REP(i, 1, n) a[i] = read(), tot += a[i];
        M = tot / n;
        REP(i, 1, n - 1) c[i] = c[i - 1] + a[i] - M;
        sort(c, c + n); tot = c[n / 2];
        REP(i, 0, n - 1) ans = ans + abs(tot - c[i]);
        printf("%lld\n", ans);
    }

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值