【BZOJ1045】[HAOI2008]糖果传递

【BZOJ1045】[HAOI2008]糖果传递

题面

bzoj

洛谷

题解

根据题意,我们可以很容易地知道最后每个人的糖果数\(ave\)

设第\(i\)个人给第\(i-1\)个人\(X_i\)个糖果(\(i=1\)则表示第1个人个第\(n\)个人,\(X_i<0\)则表示\(i-1\)\(i\)糖果\(-X_i\))

由题,第一个人最后\(A_1-X_1+X_2=ave\)

\(\Rightarrow x_2=ave-A_1+X_1\)(设\(C_1=A_1-ave\),下面同理)

\(\Rightarrow x_2=x_1-C_1\)

\(\Rightarrow x_3=x_1-C_2\)

\(......\)

\(\Rightarrow x_n=x_1-C_{n-1}\)

题目变为求\(x_1\)使\(|x1|+|x1-c_1|+|x_1-c_2|+...+|x_1-c_{n-1}|\)最小

可知\(x_1\)取中间值时原式最小

代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring> 
#include <cmath> 
#include <algorithm>
using namespace std;
typedef long long ll; 
const int MAX_N = 1e6 + 5; 
int N;
ll A[MAX_N], C[MAX_N], tot, M; 
int main () {
    while (scanf("%d", &N) != EOF) {
        tot = 0;
        for (int i = 1; i <= N; i++) { scanf("%lld", &A[i]); tot += A[i]; }
        M = tot / N; 
        C[0] = 0; 
        for (int i = 1; i < N; i++) C[i] = C[i - 1] + A[i] - M; 
        sort(&C[0], &C[N]);
        ll mid = C[N / 2], ans = 0; 
        for (int i = 0; i < N; i++) ans += abs(mid - C[i]); 
        printf("%lld\n", ans); 
    } 
    return 0; 
} 

转载于:https://www.cnblogs.com/heyujun/p/10178217.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值