题面
解法
环形均分纸牌
和这道题是一模一样的
时间复杂度:\(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;
}
原文地址:https://www.cnblogs.com/copperoxide/p/9478264.html
时间: 2024-10-11 08:44:23