【BZOJ1045】[HAOI2008]糖果传递

【BZOJ1045】[HAOI2008]糖果传递

题面

bzoj

洛谷

题解

根据题意,我们可以很容易地知道最后每个人的糖果数\(ave\)

设第\(i\)个人给第\(i-1\)个人\(X_i\)个糖果(\(i=1\)则表示第1个人个第\(n\)个人,\(X_i<0\)则表示\(i-1\)\(i\)糖果\(-X_i\))

由题,第一个人最后\(A_1-X_1+X_2=ave\)

\(\Rightarrow x_2=ave-A_1+X_1\)(设\(C_1=A_1-ave\),下面同理)

\(\Rightarrow x_2=x_1-C_1\)

\(\Rightarrow x_3=x_1-C_2\)

\(......\)

\(\Rightarrow x_n=x_1-C_{n-1}\)

题目变为求\(x_1\)使\(|x1|+|x1-c_1|+|x_1-c_2|+...+|x_1-c_{n-1}|\)最小

可知\(x_1\)取中间值时原式最小

代码

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring> 
#include <cmath> 
#include <algorithm>
using namespace std;
typedef long long ll; 
const int MAX_N = 1e6 + 5; 
int N;
ll A[MAX_N], C[MAX_N], tot, M; 
int main () {
	while (scanf("%d", &N) != EOF) {
		tot = 0;
		for (int i = 1; i <= N; i++) { scanf("%lld", &A[i]); tot += A[i]; }
		M = tot / N; 
		C[0] = 0; 
		for (int i = 1; i < N; i++) C[i] = C[i - 1] + A[i] - M; 
		sort(&C[0], &C[N]);
		ll mid = C[N / 2], ans = 0; 
		for (int i = 0; i < N; i++) ans += abs(mid - C[i]); 
		printf("%lld\n", ans); 
	} 
	return 0; 
} 
posted @ 2018-12-26 11:33  heyujun  阅读(174)  评论(1编辑  收藏  举报