UVA

来源:互联网 发布:清华大学网络学堂app 编辑:程序博客网 时间:2024/06/13 11:36

Spreading the Wealth

 UVA - 11300 
题意:n个人围一个圈,每个人手上有一些金币,最终要使每个人的金币数量相同求最少的转让数量
设 x[i]表示每个人的转让数量,a[1]-x[1]+x[2]=M,x[2]=M-a[1]+x[1],将M-x[1]表示成常量 C[i],则 可以把每个人的转让量给表示出来
最后要使  abs(x1)+abs(x1-c[i-1])+abs(x1-c[i-2])...这个表达式的几何意义就是求一个线段上的点到n个点的最小距离,这个点是中位数
#include <iostream>#include <bits/stdc++.h>using namespace std;const int N = 1e6+7;typedef long long LL;LL a[N], c[N];int main(){    int n;    while(scanf("%d", &n)!=EOF)    {        LL sum=0;        for(int i=1;i<=n;i++)        {            scanf("%lld", &a[i]);            sum+=a[i];        }        LL m=sum/n;        c[0]=0;        for(int i=1;i<n;i++) c[i]=c[i-1]+a[i]-m;        sort(c,c+n);        LL x1=c[n/2], ans=0;        for(int i=0;i<n;i++)        {            ans+=abs(c[i]-x1);        }        cout<<ans<<endl;    }    return 0;}


0 0
原创粉丝点击