您的位置:首页 > 其它

uva11300 Spreading the Wealth

2016-11-07 15:31 253 查看
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 t inside an unsigned 64 bit integer. Output For

each input, output the minimum number of coins that must be

transferred on a single line.

设第i个人给第i-1个人的钱为xi(xi<0表示第i-1个人给第i个人钱)。计算出最后每个人应该有的钱m,解方程得xi=x1-(a1+a2+ … +a(i-1)-(i-1) * m)=x1-ti。

答案就是让|x1-t1|+|x1-t2|+…+|x1-tn|最小,所以x1应该取这些t中的中位数。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
#define LL long long
LL a[1000010],f[1000010],m;
int n;
LL rd()
{
LL x=0;
char c=getchar();
while (c<'0'||c>'9') c=getchar();
while (c>='0'&&c<='9')
{
x=x*10+c-'0';
c=getchar();
}
return x;
}
int main()
{
int i;
LL ans,x;
while (scanf("%d",&n)==1)
{
for (i=1;i<=n;i++)
a[i]=rd();
m=0;
for (i=1;i<=n;i++)
m+=a[i];
m/=n;
f[1]=0;
for (i=2;i<=n;i++)
f[i]=f[i-1]+a[i-1]-m;
sort(f+1,f+n+1);
x=f[(n+1)/2];
ans=0;
for (i=1;i<=n;i++)
ans+=abs(f[i]-x);
cout<<ans<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数学推导