24h購物| | PChome| 登入
2013-07-10 06:53:56| 人氣639| 回應0 | 上一篇 | 下一篇

[UVA][math] 11300 - Spreading the Wealth

推薦 0 收藏 0 轉貼0 訂閱站台


 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. 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 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

翻譯:http://luckycat.kshs.kh.edu.tw/homework/q11300.htm

現在每個人的財產為 A1, A2, A3, ..., An
最後均分的錢為 sigam(Ai)/n = M
設每個人都向左傳遞的交易量為 xi,即 A1 往左丟 x1, A2 往左丟 x2, ...
x 的正負號表示往左、往右傳,因此要最小化 |x1|+|x2|+|x3| ... + |xn|
但因為每個都最後都具有 M 元,轉換一下方程,
對 A1,M = A1 - x1 + x2 => x2 = M - (A1-x1) = x1 - (A1-M)

對 A2,M = A2 - x2 + x3 => x3 = M - (A2-x2) = x1 - (A1+A2-2M)
對 A3,M = A3 - x3 + x4 => x4 = M - (A3-x3) = x1 - (A1+A2+A3-3M)

...
對 An,M = An - xn + x1 => xn = M - (An-x1) = x1 - (sigma(Ai)-(n-1)M)

因此最後為 |x1|+|x1-(A1-M)|
+|x1-(A1+A2-2M)|+ ... + ...
將原本的輸入轉換一下數據,找中位數代入計算就會是答案了。

#include <stdio.h>
#include <algorithm>
using namespace std;
long long A[1000005];
int main() {
    int n, i;
    while(scanf("%d", &n) == 1) {
        long long sum = 0;
        for(i = 0; i < n; i++) {
            scanf("%lld", &A[i]);
            sum += A[i];
            A[i] = sum;
        }
        long long M = sum/n;
        for(i = 0; i < n-1; i++)
            A[i] = A[i]-(i+1)*M;
        sort(A, A+n-1);
        long long mid = A[(n-1)/2];
        long long ret = 0;
        ret += mid;
        if(ret < 0) ret = -ret;
        for(i = 0; i < n-1; i++) {
            if(A[i] > mid)  ret += A[i]-mid;
            else            ret += mid-A[i];
        }
        printf("%lld\n", ret);

    }
    return 0;
}

台長: Morris
人氣(639) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: UVA |
此分類下一篇:[UVA][最短路] 11377 - Airport Setup
此分類上一篇:[UVA] 11230 - Annoying painting tool

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文