• 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

     

  • 相关阅读:
    KindEditor粘贴word图片且图片文件自动上传功能
    umeditor粘贴word图片且图片文件自动上传功能
    百度Web编辑器粘贴word图片且图片文件自动上传功能
    PHP大文件上传支持断点上传解决方案
    PHP大文件上传支持断点上传教程
    matlab函数——shading函数
    Matlab griddata函数功能介绍
    戴尔 SE2416HM
    visio中如何旋转形状
    axios的封装与异常处理(async/await)
  • 原文地址:https://www.cnblogs.com/ghosh/p/12667832.html
Copyright © 2020-2023  润新知