环形均分纸牌
普通的均分纸牌前缀和的总和就是答案。
但是这里是环形的,要断开的位置需要最佳,我们把每个数减去sum/n,这样总的前缀和就为0了,若在第k个数之后把环断开,环形前缀和可以统一写成s[i]-s[k]
运用环形前缀和的技巧,排序后找中位数可得到最优的断开环的位置。
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
int X = 0, w = 0; char ch = 0;
while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
A ans = 1;
for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
return ans;
}
const int N = 1000005;
ll a[N], pre[N];
int main(){
int n = read();
ll sum = 0;
for(int i = 1; i <= n; i ++){
cin >> a[i];
sum += a[i];
}
ll t = sum / n;
for(int i = 1; i <= n; i ++) a[i] -= t;
for(int i = 1; i <= n; i ++) pre[i] = pre[i - 1] + a[i];
sort(pre + 1, pre + n + 1);
int k = (n + 1) / 2; ll ans = 0;
for(int i = 1; i <= n; i ++){
ans += llabs(pre[i] - pre[k]);
}
printf("%lld\n", ans);
return 0;
}