zoukankan      html  css  js  c++  java
  • 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

     

  • 相关阅读:
    C#线程类Thread初步
    无限级分类存储过程版
    C#多线程编程实例实战
    数据库里阻塞和死锁情况 看那里死锁的存储过程
    预防按钮的多次点击 恶意刷新
    .net2.0文件压缩/解压缩
    HttpHandler和HttpModule入门
    反射,枚举,绑定下拉框
    在C#里关于定时器类
    判断上传的图片文件格式是否合法不是用后缀做的判断
  • 原文地址:https://www.cnblogs.com/ghosh/p/12667832.html
Copyright © 2011-2022 走看看