【P2512 [HAOI2008]糖果传递】题解

题目链接

题目

n 个小朋友坐成一圈,每人有 ai 个糖果。每人只能给左右两人传递糖果。每人每次传递一个糖果代价为 1

思路

xi 表示第 i 个人传给前一个人的糖果数,负数则是反向传。

可以列出方程,然后依次把 xix1 表示出来,再设 ci=j=1i1(aja¯),然后最终答案就是求 |x1ci|,即让 xic 的中位数。

Code

// Problem: P2512 [HAOI2008]糖果传递
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P2512
// Memory Limit: 125 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;
ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
//#define M
//#define mo
//#define N
struct node
{
	int k, id; 
}c[1000010]; 
int n, m, i, j, k; 
int ave, ans, x_1, sum; 
int a[1000010]; 

bool cmp(node x, node y)
{
	return x.k<y.k; 
}

bool Cmp(node x, node y)
{
	return x.id<y.id; 
}

signed main()
{
//	freopen("tiaoshi.in", "r", stdin); 
//	freopen("tiaoshi.out", "w", stdout); 
	n=read(); 
	for(i=1; i<=n; ++i) a[i]=read(); 
	for(i=1; i<=n; ++i) sum+=a[i]; 
	ave=sum/n; sum=0; 
	for(i=1; i<=n; ++i)
	{
		c[i].k=sum; 
		c[i].id=i; 
		sum+=(ave-a[i]); 
	}
	sort(c+1, c+n+1, cmp); 
	x_1=c[(n+1)/2].k; 
	sort(c+1, c+n+1, Cmp); 
	for(i=1; i<=n; ++i)
		ans+=abs(x_1-c[i].k); 
	printf("%lld", ans); 
	return 0; 
}

posted @   zhangtingxi  阅读(85)  评论(0编辑  收藏  举报
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示