题意:
圆桌旁坐着 n 个人,每个人有一定数量的金币,金币总数能被 n 整除。每个人可以给他左右相邻的人一些金币,最终使得每个人的金币数目相等。你的任务是求出被转手的金币数量的最小值。n <= 1000000。
SampleInput
3
100
100
100
4
1
2
5
4
SampleOutput
0
4
利用了方程的思想,设A[i] 为第 i 个人的初始金币,设 xi 为第 i 个人一共给上一个人的金币,设 ave 为每个人最后的金币数,所以说可以得到 n 个方程 Ai - xi + x(i+1) = ave 然而第 n 个方程并没有用qwq,因为可以通过前 n-1 个方程推导出。我们设 Ci = xi - ave,那么最后答案就是 Σ|x1 - Ci|,问题就变成了如何取 x1 使这个式子的值最小,显然取中位数就好。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#define LL long long
using namespace std;
const int Max = 2001000;
LL A[Max],C[Max];
int main()
{
int n;
while(scanf("%d",&n) != EOF)
{
memset(A,0,sizeof(A));
memset(C,0,sizeof(C));
LL sum = 0;
for(int i = 1 ; i <= n ; i ++)
scanf("%lld",&A[i]) , sum += A[i];
LL ave = sum / n;
for(int i = 1 ; i < n ; i ++)
C[i] = C[i-1] + A[i] - ave;
sort(C,C + n);
LL x = C[n/2];
LL ans = 0;
for(int i = 0 ; i < n ; i ++)
ans += abs(x - C[i]);
printf("%lld\n",ans);
}
return 0;
}
/*
3
100
100
100
4
1
2
5
4
*/
传送门:http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=33899