1. 程式人生 > >【BZOJ3293】[Cqoi2011]分金幣【絕對值不等式】【中位數】【數形結合】

【BZOJ3293】[Cqoi2011]分金幣【絕對值不等式】【中位數】【數形結合】

/* Pigonometry */
#include <cstdio>
#include <algorithm>

using namespace std;

typedef long long LL;

const int maxn = 1000005;

int n, num[maxn];
LL C[maxn], M;

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline LL llabs(LL x) {
	return x > 0 ? x : -x;
}

int main() {
	n = iread();
	for(int i = 1; i <= n; i++) num[i] = iread(), M += num[i];

	M /= n;
	C[0] = 0;
	for(int i = 1; i < n; i++) C[i] = C[i - 1] + num[i] - M;
	sort(C, C + n);

	LL ans = 0, mid = C[n >> 1];
	for(int i = 0; i < n; i++) ans += llabs(mid - C[i]);

	printf("%lld\n", ans);
	return 0;
}