地址:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=2275
题意:将所有人的硬币进行一次平均分配,这里要注意的是,每个人只能和左右相邻的人交换硬币,而且这些人组成的是一个环
解法:
首先求出平均数为M
每个人初始的硬币为Ai
那么对于1,他能给予4号x1个硬币,并从2号出得到x2个硬币,那么对于1可得Ai-x1+x2 = M
同理可得An-xn+x1 = M
对上述的式子进行转化,可得
1:x2 =x1-C1 (C1 = A1 - M)
2:x3 = M-A2+x2 = 2M-A1-A2+x1 = x1-x2
...
最后所求为
|x1| + |x1-C1|+...+|x1-Cn-1|,要求这个最小,那么就是要x1为这些数的中位数
求出x1,答案也就出来了
#include <stdio.h>
#include <algorithm>
using namespace std;
const int maxn = 1000005;
long long a[maxn],c[maxn];
int main()
{
int n,i;
while(~scanf("%d",&n))
{
long long sum = 0;
c[0] = 0;
for(i = 1; i<=n; i++)
{
scanf("%lld",&a[i]);
sum+=a[i];
}
sum = sum/n;
for(i = 1; i<n; i++)
{
c[i] = c[i-1]+a[i]-sum;
}
sort(c,c+n);
long long x = c[n/2],ans = 0;
for(i = 0; i<n; i++)
{
int k;
k = x-c[i];
if(k<0)
k = -k;
ans+=k;
}
printf("%lld\n",ans);
}
return 0;
}