bzoj3293/1045 [Cqoi2011]分金幣/[HAOI2008] 糖果傳遞 貪心

圓桌上坐着n個人,每人有一定數量的金幣,金幣總數能被n整除。每個人可以給他左右相鄰的人一些金幣,最終使得每個人的金幣數目相等。你的任務是求出被轉手的金幣數量的最小值。n<=1e6.

這個是劉汝佳藍書P4的原題,還蠻巧妙的。

證明這裏也有

http://blog.csdn.net/ycdfhhc/article/details/45437677

#include<bits/stdc++.h>
#define LL long long
#define clr(x,i) memset(x,i,sizeof(x))
using namespace std;
const int N=1000005;
LL n,a[N],c[N],tot;
int main()
{
	scanf("%lld",&n);
	for(int i=1;i<=n;i++){
		scanf("%lld",&a[i]);
		tot+=a[i];
	}
	tot/=n;
	for(int i=2;i<=n;i++)
	  c[i]=c[i-1]+a[i-1]-tot;
	sort(c+1,c+n+1);
	
	LL m=c[(n+1)/2],ans=0;
	for(int i=1;i<=n;i++)
	  ans+=abs(c[i]-m);
	printf("%lld",ans);
	return 0;
}


發佈了39 篇原創文章 · 獲贊 4 · 訪問量 9471
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章