$Luogu2512/CH122/AcWing122$糖果传递 模拟
$Description$
有$n$个小朋友坐成一圈,每人有$a_i$个糖果.
每人只能给左右两人传递糖果.
每人每次传递一个糖果代价为$1$.
求使所有人获得均等糖果的最小代价.
$Sol$
感觉超级似曾相识,大概是寒假做过的题目.
求出平均数$x$,然后$a_i-=x$
设$i$小朋友给$i+1$小朋友$b_i$个糖果,特别地,$b_n$表示第$n$个小朋友给第$1$个小朋友的糖果.
$b_n+a_1-b_1=0\ \Leftrightarrow\ b_1=a_1+b_n=s_1+b_n$
$b_1+a_2-b_2=0\ \Leftrightarrow\ b_2=a_2+b_1=a_1+a_2+b_n=s_2+b_n$
答案为$\left |b_1 \right |+\left |b_2 \right |+....+\left |b_n \right |$
即为$\left |s_1+b_n \right |+\left |s_2+b_n \right |+....+\left |s_n+b_n \right |$
就是$-b_n$到$s_1,s_2,....,s_n$的距离之和,要使之最小,$-b_n$就为$s_1,s_2,....,s_n$的中位数.
$over$
$Code$
#include<bits/stdc++.h>
#define il inline
#define Rg register
#define go(i,a,b) for(Rg int i=a;i<=b;i++)
#define yes(i,a,b) for(Rg int i=a;i>=b;i--)
#define ll long long
#define db double
using namespace std;
il int read()
{
int x=,y=;char c=getchar();
while(c<''||c>''){if(c=='-')y=-;c=getchar();}
while(c>=''&&c<=''){x=(x<<)+(x<<)+c-'';c=getchar();}
return x*y;
}
const int N=1e6+;
int n,a[N];
ll as,s[N];
int main()
{
n=read();
go(i,,n)a[i]=read(),s[n]+=a[i];
Rg int ave=s[n]/n,qwq;
go(i,,n)a[i]-=ave,s[i]=s[i-]+a[i];
sort(s+,s+n+);
qwq=-s[n/+];//qwq=-b[n]
go(i,,n)as+=abs(s[i]+qwq);
printf("%lld\n",as);
return ;
}
随机推荐
- git 本地仓库操作
一.git对象模型和存储 二.常用命令 1)git checkout branch 切换分支 假设现在有两个分支,master和dev分支 i dev分支上没有readme.txt 在master分支 ...
- 使用 Laravel-Excel 进行 CSV/EXCEL 文件读写
https://blog.csdn.net/yiluohan0307/article/details/80229978 http://www.ptbird.cn/laravel-excel-csv.h ...
- ACM感想、
从15年10月开始搞ACM,到如今的16年4月底,已经接近半年了. 大一下学期开始ACM组的人员就不断减少,有的因为坚持不下,有的因为不喜欢,有的没留下理由就走了, 瞬间感觉实验室空了很多很多.现在常 ...
- 【DCN】路由操作
offset */interface in/out access-list/prefix-list <1-16> // 修改路由偏移量 RIP偏移列表 ...
- jq杂项方法/工具方法----trim() html() val() text() attr()
https://www.cnblogs.com/sandraryan/ $.trim() 函数用于去除字符串两端的空白字符.在中间的时候不会去掉. var str = ' 去除字符串左右两端的空格,换 ...
- vector容器、
一. vector 向量容器1. 创建 vector 对象(1)不指定容器大小vector<int> V;(2)指定容器大小vector<int> V(10);(3) ...
- 2018-8-10-git-提交添加-emoij-文字
title author date CreateTime categories git 提交添加 emoij 文字 lindexi 2018-08-10 19:16:52 +0800 2018-2-1 ...
- Python--day40--全局解释器锁
1,起一百个线程和起一百个进程所花的时间对比(开启效率的较量): import time from threading import Thread from multiprocessing impor ...
- Redux 初始化完整结构
文件管理 目录文档 ★★★index.js★★★ ★★★app.js★★★ ★★★store->index.js★★★ ★★★actions->index.js★★★ ★★★store-& ...
- H3C DHCP服务器基本配置示例