现在的位置: 首页 > 综合 > 正文

UVA11300 Spreading the Wealth

2013年09月13日 ⁄ 综合 ⁄ 共 1510字 ⁄ 字号 评论关闭

                                                                                                         Spreading
the Wealth 

Problem

A Communist regime is trying to redistribute wealth in a village. They have have decided tosit everyone around a circular table. First, everyone has converted all of their properties tocoins 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 rightand a number coins to the person on his left, such that in the end, everyone has thesame 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.

The 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 fit inside anunsigned 64 bit integer.

The Output

For each input, output the minimum number of coins that must be transferred on a single line.

Sample Input

3
100
100
100
4
1
2
5
4

Sample Output

0
4


解题思路:本题运用中位数,先求均值,以确定移动情况,后求差值,确定移动具体数量,最后用中位数,确定移动定点(相当于参照点)。
a[n]给她右边的人xn个金币,她左边的人给她xn+1个金币,av=a[n]-xn+xn+1.


#include<cstdio>
#include<algorithm>
using namespace std;
long long a[1000001],c[1000001];
int main()
{
    int n,i,j;
    long long sum,av;
    while(scanf("%d",&n)!=EOF)
    {
        sum=0;
        for(i=1;i<=n;i++)
        {
            scanf("%lld",&a[i]);
            sum+=a[i];
        }
        av=sum/n;   //求均值
        c[0]=0;
        for(i=1;i<=n;i++)
            c[i]=c[i-1]+a[i]-av;    //求差值
        sort(c,c+n);
        int x=c[n/2];       //求中位数
        sum=0;
        for(i=0;i<n;i++)        //求移动情况
            sum+=abs(x-c[i]);
        printf("%lld\n",sum);
    }
    return 0;
}

 

抱歉!评论已关闭.