欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

圆桌均分硬币 ——(推导式子)

程序员文章站 2022-06-22 08:29:40
A * regime is trying to redistribute wealth in a village. They have have decided to sit everyonearound a circular table. First, everyone has c ......

a * regime is trying to redistribute wealth in a village. they have have decided to sit everyonearound 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, eachperson 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 everyonehas the same number of coins.

input

there is a number of inputs. each input begins withn(n<1000001), the number of people in thevillage.nlines follow, giving the number of coins of each person in the village, in counterclockwiseorder 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.

sample input

3

100

100

100

4

1

2

5

4

sample output

0

4

题意:圆桌坐着n个人,每个人有一定的金币,金币总数能被n整除。每个人能给左右相邻的人一些金币,最终使得每个人的金币数目相等,求被转手金币数量的最小值。

设:

  • xi表示i号给i-1号xi金币(若xi为负,这表示i-1号给i号(-xi)个金币)
  • ai表示i号一开始持有的金币

则:

  • 对与第1个人:a1-x1+x2=m  ->(移项) x2=x1-(a1-m)(用x1减是为了最后得出一个距离的式子);
  • 对于第2个人:a2-x2+x3=m ->x3=x2-(a2-m) -> x3=x1-(a1+a2-2m)

  类似的去递推:

  xi=x1-(a1+a2+......+a(i-1)-m*(i-1)) 

  令c1=a1-m,c2=a1+a2-m*2......ci=a1+a2+......+ai-m*i;(每个c都可以求出)

  所以 我们可以把x的整个数组换成用x1和c表示:

  x1=x1;

  x2=x1-c1;

  一直到 xn=x1-c(n-1);

所以我们的答案应该是 |x1|+|x2|+|x3|+……+|xn|的最小值;

->|x1|+|x1-c1|+|x1-c2|+……+|x1-c(n-1)|的最小值

首项|x1|可以是|x1-0|(我们可以让c0=0)

->|x1-c0|+|x1-c1|+|x1-c2|+……+|x1-c(n-1)|

故当x1取c数组的中间值时,结果最小。

注意:|x1 – ci|在数轴上就是x1到ci的距离,所以问题变成了:给定数轴上的n个点,找出一个到它们的距离之和尽量小的点。

这个最优的x1就是这些数的“中位数”。即排序以后位于中间的数。

代码:

 1 #include <cstdio>
 2 #include <cmath>
 3 #include <cstring>
 4 #include <algorithm>
 5 using namespace std;
 6 const int maxn=1000005;
 7 long long a[maxn],c[maxn],tot,m;
 8 int main()
 9 {
10 //    freopen("1.in","r",stdin);
11        int n;
12        while(scanf("%d",&n)!=eof){
13        tot=0;
14        for(int i=1;i<=n;i++){
15           scanf("%lld",&a[i]);
16           tot+=a[i];
17        }
18        m=tot/n;//求平均值
19        c[0]=0;
20        for(int i=1;i<n;i++)
21                c[i]=c[i-1]+a[i]-m;//c数组算出
22            sort(c,c+n);//记得排序
23            long long x1=c[n/2];//x1算出,每人的硬币移动次数皆可表示
24            long long ans=0;
25            for(int i=0;i<n;i++)
26           ans+=(x1-c[i]>=0?x1-c[i]:c[i]-x1);
27        printf("%lld\n",ans);
28    }
29    return 0;
30 }