UVA11300 Spreading the Wealth

 F. Spreading the Wealth 

Problem

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.

The Input

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.

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

 


Problem setter: Josh Bao

题目大意:N个人围在一张圆桌上,位置编号为1~N,分给每人a[i]金币,每个人给相邻的左边的人一些金币,相邻的右边的人一些金币,最后使得每个人手里持有的金币相等。问最少有多少金币需要进行转移。

题解:中数问题。。。需要进行一定的推导。

设M为最终没人获得的金币的平均数,x[i]为给第i-1个人的金币数。

那么可以发现:

x[1]=x[1];

x[2]=x[1]-(a[1]-M);

x[3]=x[1]-(a[1]-M)-(a[2]-M);

.......

x[n]=x[1]-(a[1]-M)...(a[n-1]-M);

设c[i]=c[i-1]+(a[i]-M);

则x[i]=x[1]-c[i-1];

最小转移量ans=min(|x[1]]+|x[2]|+|x[3]|+....|x[n]|)

            =min(|x[1]|+|x[1]-c[1]|+|x[1]-c[2]|+....|x[1]-c[n-1]|)

显然x[1]等于中位数的时候ans会最小。

View Code
 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 #define MAXN 1000001
 5 long long c[MAXN+5],ans,m,x1;
 6 long a[MAXN+5];
 7 int compare(const void*a,const void*b)
 8 {
 9     return*(int*)a-*(int*)b;
10 }
11 int main(void)
12 {
13     long i,n;
14     while(scanf("%ld",&n)==1)
15     {
16         m=0;
17         for(i=0; i<n; i++)
18         {
19             scanf("%ld",&a[i]);
20             m+=a[i];
21         }
22         m/=n;
23         memset(c,0,sizeof(c));
24         for(i=1; i<n; i++)
25             c[i]=c[i-1]+a[i]-m;
26         qsort(c,n,sizeof(long long),compare);
27         x1=c[n>>1];
28         ans=0;
29         for(i=0; i<n; i++)
30             ans+=abs(x1-c[i]);
31         printf("%lld\n",ans);
32     }
33     return 0;
34 }
原文地址:https://www.cnblogs.com/zjbztianya/p/2945328.html