天天看点

UVA 之11300 - Spreading the Wealth

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.

there is a number of inputs. each input begins with n(n<1000001), the number of people in the village. nlines 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 an unsigned 64 bit integer.

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

【思路】:

UVA 之11300 - Spreading the Wealth
UVA 之11300 - Spreading the Wealth
UVA 之11300 - Spreading the Wealth

c0 = 0

c1 = a1 - m = c0 + a1 - m

c2 = a1 - m + a2 - m = c1 + a2 - m

............

cn = an-1 - m + an - m = cn-1 + an - m

规律:cn  = cn-1 + an - m

【代码】:

[cpp] 

/********************************* 

*   日期:2013-4-21 

*   作者:sjf0115 

*   题号: 题目11300 - spreading the wealth 

*   来源:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&itemid=8&category=25&page=show_problem&problem=2275 

*   结果:ac 

*   来源:uva 

*   总结: 

**********************************/  

#include<stdio.h>  

#include<stdlib.h>  

int money[1000001],c[1000001];  

int cmp(const void *a,const void *b){  

    return *(int *)a - *(int *)b;  

}  

//绝对值  

int abs(int a,int b){  

    if(a < b){  

        return b - a;  

    }  

    else{  

        return a - b;  

int main ()  

{  

    long long int i,n,min,sum,m;  

    //freopen("c:\\users\\xiaosi\\desktop\\acm.txt","r",stdin);  

    while(scanf("%lld",&n) != eof){  

        sum = 0;  

        min = 0;  

        //n个人  

        for(i = 0;i < n;i++){  

            scanf("%d",&money[i]);  

            sum += money[i];  

        }  

        //平均值  

        m = sum / n;  

        c[0] = 0;  

        //初始化c数组  

        for(i = 1;i < n;i++){  

            c[i] = c[i-1] + money[i] - m;  

        //排序,选择中位数  

        qsort(c,n,sizeof(int),cmp);  

        long long int x1 = c[n/2];  

        //计算转移的金币数  

            min += abs(x1,c[i]);  

        printf("%lld\n",min);  

    return 0;  

注意:int越界 用long long int 

继续阅读