• Uva 11300 Spreading the Wealth 中位数


    UVA - 11300 Spreading the Wealth

    Description

    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 fit inside an unsigned 64 bit integer.

    Output

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

    Simple Input

    3
    100
    100
    100
    4
    1
    2
    5
    4

    Simple Output

    0
    4

    题意:n个人围一圈,每人有若干个金币,每个人可以分别给相邻的两个人若干个金币,求最少的金币转移数。

    分析:如果一共有w个金币,那么每个人最后有w/n个金币。

            定义a[i]为第i个人原来的金币,x[i]为第i个人给第i+1个人的金币,A为最后每个人的金币

        那么我们可以推得a[1]+x[n]-x[1]=A

                a[2]+x[1]-x[2]=A

                a[n]+x[n-1]-x[n]=A

        移个项再代入就能得到x[2]=x[1]-(A-a[1])

                  x[3]=x[1]-(2*A-a[1]-a[3])

        我们需要求得是|x1|+|x1-b1|+|x2-b2|+……+|xn-bn|需要选择中位数

     1 #include <bits/stdc++.h>
     2 using namespace std;
     3 const int maxn = 1000001;
     4 long long n, m, a[maxn], c[maxn];
     5 int main(){
     6     while (scanf("%d", &n) == 1){
     7         long long sum = 0;
     8         for (int i = 1; i <= n; i++) scanf("%d", &a[i]), sum += a[i];
     9         int ave = sum / n;
    10         c[0] = 0;
    11         for (int i = 1; i < n; i++)
    12             c[i] = c[i - 1] + a[i] - ave;
    13         sort(c, c + n);
    14         long long x = c[n/2];
    15         long long ans = 0;
    16         for (int i = 0; i < n; i++){
    17             ans += abs(x - c[i]);
    18         }
    19         printf("%lld
    ", ans);
    20     }
    21     return 0;
    22 }
    View Code

     

  • 相关阅读:
    通过user-agent判断h5页面是在哪个手机App(QQ、微信、支付宝)下打开的
    vscode格式化插件
    简单直接,“NODE_ENV”总结
    NativeScript又一个Hybrid技术(附与Weex,ReactNative比较)
    ReactNative开发中遇到的问题记录
    两个在线编辑网站runjs和jsbin
    go 如何单测
    go语法-type等
    go语法-结构体和接口-细节
    解决 Webstorm 每次更新 Git 代码都要输入密码的问题
  • 原文地址:https://www.cnblogs.com/ghosh/p/12667832.html
Copyright © 2020-2023  润新知