zoukankan      html  css  js  c++  java
  • UVA

    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

    思路分析:

      由于硬币总数比上总人数是一个整数,我们用m来表示这个数,即在多次分完硬币之后,每个人手中都有m个硬币,我们用A数组来表示

    每个人在分硬币之前的每个人的硬币数,用x数组来表示第i个人给他前一个人的硬币数,那么就有A[i]-x[i]+x[i+1]=m,即x[i+1]=x[i]-A[i]+m;

    将xi往后推则有:

    x2=x1-A[i]+m;
    x3=x2-A2+m=x1-A[1]-A[2]+2*m;
    x4=x3-A3+m=x1-A[1]-A[2]-A[3]+3*m;
    于是我们为了简化这些式子,用C[1]=A[1]-m,C[2]=c[1]+A[2]-m ··· ···
    则有

    x2=x1-C[1];
    x3=x1-C[2];
    x4=x1-C[3];
    ···
    我们最终要求的就是|x1|+|x1-C1|+|x1-C2|+···+|x1-Cn-1|最小,则我们取得x1应该为ci的中位数,最终统计答案即可。

    开long long

    附上代码:

     1 #include<cstdio>
     2 #include<cstring>
     3 #include<algorithm>
     4 using namespace std;
     5 const int N=1e6+10;
     6 long long a[N],c[N],m,n,sum;
     7 int main(){
     8     while(scanf("%lld",&n)==1){
     9         memset(a,0,sizeof(a));
    10         memset(c,0,sizeof(c));
    11         sum=0;       //用于计算sum 
    12         for(int i=1;i<=n;++i){
    13             scanf("%lld",&a[i]);
    14             sum+=a[i];
    15         }
    16         m=sum/n;
    17         for(int i=1;i<=n;++i)
    18             c[i]=c[i-1]+a[i]-m; //由前面的公式得到 
    19         sort(c+1,c+n+1);
    20         long long x1=c[n/2],ans=0; //x1取c[]的中位数 
    21         for(int i=1;i<=n;++i)
    22             ans+=abs(x1-c[i]);//统计答案. 
    23         printf("%lld
    ",ans);
    24     }
    25     return 0;
    26 }
  • 相关阅读:
    go通道小案例
    go执行cmd命令并获取输出内容
    vue快速生成二维码
    vue.js数字简化 万转化k显示
    uniapp实现小程序获取用户信息
    实现图片预加载功能
    C# MD5加密字符串方法
    一个封装的 HttpClientHelper
    简易通过队列存储并异步打日志实现
    变量
  • 原文地址:https://www.cnblogs.com/li-jia-hao/p/12663607.html
Copyright © 2011-2022 走看看