题解 P2512 【[HAOI2008]糖果传递】
LiRewriter · · 题解
我觉得楼下大佬抄hzwer不太好吧
虽说我大概是抄进阶指南
首先这道题是一个模型,我们称之为环形均分纸牌。显然这个模型是出自luogu1031那道均分纸牌,没有过的可以先过一下。
先来看不是环形的情况。
假设总和为
但是这样并不方便维护,我们考虑整体和隔离的思想。将前i个看做一个整体,显然前i个内部的均分是不会改变其整体结构的,因而对于该体系来说,想要达到平均数结构,就必须与下一个体系交换足够的纸牌,而交换数量就是
如果让每个人的数量都减去
现在考虑一种变形:如果这里的纸牌是环形的呢?
对于环形问题,首先考虑切开。假定我们切开的东西是
由于均分之后,
因而,这里我们要求的东西是
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long LL;
LL sum[1000003], S;
inline void read(LL &x) {
x = 0; char c = getchar();
while(!isdigit(c)) c = getchar();
while(isdigit(c)) x = x * 10 + c - '0', c = getchar();
}
int main() {
LL n, ans = 0;
read(n);
for(int i = 1; i <= n; ++i) read(sum[i]), S += sum[i];
LL ave = S / n;
for(int i = 1; i <= n; ++i) sum[i] -= ave;
for(int i = 1; i <= n; ++i) sum[i] = sum[i - 1] + sum[i];
int m = (n + 1) / 2;
nth_element(sum + 1, sum + m, sum + n + 1);
for(int i = 1; i <= n; ++i) ans += abs(sum[i] - sum[m]);
cout<<ans<<endl;
return 0;
}