n个人每个人有一定金币,金币数量能被n整除。
每个人可以给他左右相邻的人一些金币,使得最终每个人金币数相等。(n个人围成一个圈)
求被转手金币最少。
看图,希望所有xi的绝对值之和最小:|x1| + |x1-C1| + …. + |x1-Cn-1|
有几个个点:
1.题目出来都会有数学解题方法。。
2.给点数轴上n个点,找出一个它们的距离之和尽量小的点:中位数。中位数可以在线性时间内求出,“快速选择”算法。
3.输入大数据的时候,scanf比cin要快。
#include"stdafx.h"
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 1000000 + 10;
long long A[maxn], C[maxn], tot, M;
int main()
{
int n;
while (scanf("%d", &n) == 1)
{
tot = 0;
for (int i = 0; i < n; i++)
{
scanf("%lld", &A[i]);
tot += A[i];
}
M = tot / n;
C[0] = 0;
for (int i = 1; i < n; i++)
{
C[i] = C[i - 1] + A[i] - M;
}
sort(C, C + n);
long long x1 = C[n / 2];
long long ans = 0;
for (int i = 0; i < n; i++)
ans += abs(x1 - C[i]);
printf("%lld\n", ans);
}
}