uva11300 Spreading the Wealth

来源:互联网 发布:java常用算法手册豆瓣 编辑:程序博客网 时间:2024/05/29 18:47

A Communist regime is trying to redistribute wealth in a village. They
have have decided to sit everyone around a circular table. First,
everyone has converted all of their properties to coins of equal
value, such that the total number of coins is divisible by the number
of people in the village. Finally, each person gives a number of coins
to the person on his right and a number coins to the person on his
left, such that in the end, everyone has the same number of coins.
Given the number of coins of each person, compute the minimum number
of coins that must be transferred using this method so that everyone
has the same number of coins. Input There is a number of inputs. Each
input begins with n ( n< 1000001), the number of people in the
village. n lines follow, giving the number of coins of each person in
the village, in counterclockwise order around the table. The total
number of coins will t inside an unsigned 64 bit integer. Output For
each input, output the minimum number of coins that must be
transferred on a single line.

设第i个人给第i-1个人的钱为xi(xi<0表示第i-1个人给第i个人钱)。计算出最后每个人应该有的钱m,解方程得xi=x1-(a1+a2+ … +a(i-1)-(i-1) * m)=x1-ti。
答案就是让|x1-t1|+|x1-t2|+…+|x1-tn|最小,所以x1应该取这些t中的中位数。

#include<cstdio>#include<cstring>#include<algorithm>#include<iostream>using namespace std;#define LL long longLL a[1000010],f[1000010],m;int n;LL rd(){    LL x=0;    char c=getchar();    while (c<'0'||c>'9') c=getchar();    while (c>='0'&&c<='9')    {        x=x*10+c-'0';        c=getchar();    }    return x;}int main(){    int i;    LL ans,x;    while (scanf("%d",&n)==1)    {        for (i=1;i<=n;i++)          a[i]=rd();        m=0;        for (i=1;i<=n;i++)          m+=a[i];        m/=n;        f[1]=0;        for (i=2;i<=n;i++)          f[i]=f[i-1]+a[i-1]-m;        sort(f+1,f+n+1);        x=f[(n+1)/2];        ans=0;        for (i=1;i<=n;i++)          ans+=abs(f[i]-x);        cout<<ans<<endl;    }}
0 0