跳到正文

题解

题解:P2512 [HAOI2008] 糖果传递

OIRikka约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年7月23日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 3 分钟
题目
P2512

版本

  1. v1当前

From 洛谷P2512

设A[i]A[i]表示第ii个小朋友原有的糖果数量

nownow表示所有小朋友糖果数量的平均数(要求的)

X[i]X[i]表示第ii个小朋友向左传的糖果数量

∴\therefore由题意得:

A[1]+X[2]−X[1]=nowA[1]+X[2]-X[1]=now

(原有的+第二个传来的-我要传走的=我有的)

同理,

A[2]+X[3]−X[2]=nowA[2]+X[3]-X[2]=now

A[3]+X[4]−X[3]=nowA[3]+X[4]-X[3]=now

即A[n]+X[n+1]−X[n]=nowA[n]+X[n+1]-X[n]=now

∴\therefore变形可得

X[2]=now+X[1]−A[1]X[2]=now+X[1]-A[1],

X[3]=now+X[2]−A[2]=now+(now+X[1]−A[1])−A[2]=2now−A[1]−A[2]+X[1]X[3]=now+X[2]-A[2]=now+(now+X[1]-A[1])-A[2]=2now-A[1]-A[2]+X[1],

X[n]=now+X[n−1]−A[n−1]=(n−1)⋅now−A[1]−A[2]−....−A[n−1]+X[1]X[n]=now+X[n-1]-A[n-1]=(n-1)·now-A[1]-A[2]-....-A[n-1]+X[1]

这时我们设:

C[1]=A[1]−nowC[1]=A[1]-now,

C[2]=A[1]+A[2]−2nowC[2]=A[1]+A[2]-2now,

C[n]=A[1]+A[2]+...+A[n]−n⋅nowC[n]=A[1]+A[2]+...+A[n]-n·now

∴\therefore X[2]=now+X[1]−A[1]X[2]=now+X[1]-A[1]

X[2]−X[1]=now−A[1]X[2]-X[1]=now-A[1]

X[1]−X[2]=A[1]−nowX[1]-X[2]=A[1]-now

∵\because A[1]−now=C[1]A[1]-now=C[1]

∴\therefore X[1]−X[2]=C[1]X[1]-X[2]=C[1]

X[1]=C[1]+X[2]X[1]=C[1]+X[2]

∴\therefore X[2]=X[1]−C[1]X[2]=X[1]-C[1]

同理, X[3]=X[1]−C[2]X[3]=X[1]-C[2]

X[n]=X[1]−C[n]X[n]=X[1]-C[n]

由题意得:

∵\because 要求传递价值最小

传递一个糖果代价为11

∴\therefore 求∣X[1]∣+∣X[2]∣+...+∣X[n]∣|X[1]|+|X[2]|+...+|X[n]| (式子1)的minmin

即求传送糖果的最小值

∵\because X[n]=X[1]−C[n]X[n]=X[1]-C[n]

∴\therefore 式子一=∣X[1]−C[1]∣+∣X[1]−C[2]∣+...+∣X[1]−C[n]∣|X[1]-C[1]|+|X[1]-C[2]|+...+|X[1]-C[n]|

即求该式的minmin

∵\because C[i]C[i]已知

∴\therefore 问题转化为找出点X[i]X[i]在数轴上,使得其到每个C[i]C[i]点的距离最小,即其中位数

求出X[1]X[1]后,依据X[3]=X[1]−C[2]X[3]=X[1]-C[2]等式子,可得最终式子为: ∣X[1]∣+∣X[2]∣+...+∣X[n]∣|X[1]|+|X[2]|+...+|X[n]|

依据思路模拟可得std:std:

C++
#include <bits/stdc++.h>
using namespace std;
const int inf = 0x7fffffff;
const int N = 1e6 + 1;
long long n;
long long a[N], c[N];
long long ave, ans, mid;
int main()
{
    scanf("%lld", &n);
    for (int i = 1; i <= n; i++) 
    {
        scanf("%lld", &a[i]);
        ave += a[i];
    }
    ave /= n;
    for (int i = 1; i <= n; ++i) 
        c[i] = c[i - 1] + ave - a[i - 1];
    sort(c + 1, c + n + 1);
    mid = c[(n + 1) / 2];
    for (int i = 1; i <= n; ++i) 
    ans += abs(mid - c[i]);
    printf("%lld", ans);
    return 0;
}
原文