bzoj 1045 [HAOI2008] 糖果传递 排序

题面

题目传送门

解法

环形均分纸牌

这道题是一模一样的

时间复杂度:\(O(n\ log\ n)\)

代码

#include <bits/stdc++.h>
#define int long long
#define N 1000010
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
	x = 0; int f = 1; char c = getchar();
	while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
	while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
int a[N];
main() {
	int n, sum = 0; read(n);
	for (int i = 1; i <= n; i++)
		read(a[i]), sum += a[i];
	for (int i = 1; i <= n; i++) a[i] -= sum / n;
	for (int i = 1; i <= n; i++) a[i] += a[i - 1];
	sort(a + 1, a + n + 1); int k = (n + 1) / 2;
	int ans = 0;
	for (int i = 1; i <= n; i++) ans += abs(a[i] - a[k]);
	cout << ans << "\n";
	return 0;
}

posted @ 2018-08-14 22:06  谜のNOIP  阅读(95)  评论(0编辑  收藏  举报