题意:
环形排列的n(n<=106)个人,每人有一定量的金币。每个人可以给左右相邻的两个人金币,最终使得每
个人都有相同量的金币。求被转手的最小金币数。
思路:
感觉很复杂,解决起来非常巧妙,书上讲的很好,懒得写了,摘一段别人的
|x1 - Ci|的几何意义是数轴上一点x1到Ci的距离。所以问题转化为:给定数轴上n个点,找出一个到他们的距离之和最小的点。
这个点就是这些数中最中间的点。
#include <cstdio>
#include <cstring>
#include <algorithm>
#define fi first
#define se second
#define pii pair<int,int>
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long LL;
const int maxn = 1000000+5;
int n;
LL A[maxn], ans;
int main()
{
while(scanf("%d",&n) == 1&&n){
LL tot = 0;
for(int i = 0; i < n; ++i) scanf("%lld", &A[i]), tot += A[i];
LL ave = tot / n;
A[0] = A[0] - ave;
for(int i = 1; i < n; ++i){
A[i] = A[i-1] + A[i] - ave;
}
sort(A, A+n);
LL t = A[n/2];
ans = 0;
for(int i = 0; i < n; ++i) ans+= abs(A[i] - t);
printf("%lld\n", ans);
}
fclose(stdin);
return 0;
}