[HAOI2008]糖果传递
和题解差不多,加了点证明。
题目大意
有 个小朋友坐成一圈,每人有 个糖果。每人只能给左右两人传递糖果。每人每次传递一个糖果代价为 。
题目分析
设 表示所有小朋友糖果数量的平均数,因为所有小朋友糖果总数不会变,所以最后每个人的糖果数都会变成平均数。设 表示第 个小朋友往左传的糖果数。
若 为负数,表示向右传。
可知:
一般地:
我们只保留 :
我们引入 数组,定义:
故有:
一般地:
题目要求我们最小化 ,亦即最小化 。
将 看作数轴上的点,问题转换为找出一个点 使得所有点到 距离和最小。
结论: 为 的中位数时距离和最小。
证明:数学归纳法。
秩:区间内任意取值均使得全局最优时,默认取左端点。
当有两个数时,显然 取在两数之间的位置比较好,为了使模型一般化,我们的 取为 。此时 为 的中位数。
当有三个数时,假设排序后为 ,那么 一定在 之间,取哪里呢?发现放在之间的话, 不变,所以我们只需要最小化 。易得 时最小,此时 为 的中位数。
当有四个数时,抽象成两个数时的模型,根据我们的“秩”, 取 。
以此类推。
于是我们可以求出 , 也就不难得到了。
代码
//2022/3/10
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cstdio>
#include <climits>//need "INT_MAX","INT_MIN"
#include <cstring>//need "memset"
#include <numeric>
#include <algorithm>
#define int long long
#define enter() putchar(10)
#define debug(c,que) cerr << #c << " = " << c << que
#define cek(c) puts(c)
#define blow(arr,st,ed,w) for(register int i = (st);i <= (ed); ++ i) cout << arr[i] << w;
#define speed_up() cin.tie(0),cout.tie(0)
#define mst(a,k) memset(a,k,sizeof(a))
#define Abs(x) ((x) > 0 ? (x) : -(x))
const int mod = 1e9 + 7;
inline int MOD(int x) {
while (x < 0) x += mod;
while (x >= mod) x -= mod;
return x;
}
namespace Newstd {
char buf[1 << 21],*p1 = buf,*p2 = buf;
inline int getc() {
return p1 == p2 && (p2 = (p1 = buf) + fread(buf,1,1 << 21,stdin),p1 == p2) ? EOF : *p1 ++;
}
inline int read() {
int ret = 0,f = 0;char ch = getc();
while (!isdigit(ch)) {
if(ch == '-') f = 1;
ch = getc();
}
while (isdigit(ch)) {
ret = (ret << 3) + (ret << 1) + ch - 48;
ch = getc();
}
return f ? -ret : ret;
}
inline void write(int x) {
if(x < 0) {
putchar('-');
x = -x;
}
if(x > 9) write(x / 10);
putchar(x % 10 + '0');
}
}
using namespace Newstd;
using namespace std;
const int ma = 1e6 + 5;
int a[ma],sum[ma],c[ma];
int n,ave;
#undef int
int main(void) {
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
#endif
#define int long long
n = read();
for (register int i = 1;i <= n; ++ i) a[i] = read(),ave += a[i];
ave /= n;
for (register int i = 1;i <= n; ++ i) {
sum[i] = sum[i - 1] + a[i];
c[i] = sum[i] - i * ave;
}
sort(c + 1,c + n + 1);
int ans = 0,standard = c[n / 2];
for (register int i = 1;i <= n; ++ i) {
ans += Abs(standard - c[i]);
}
printf("%lld\n",ans);
return 0;
}
本文作者:Coros_Trusds
本文链接:https://www.cnblogs.com/Coros-Trusds/p/15991773.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步