Divide the candy evenly-2-7 more in 2021

    题目
  小A班的 n 位小朋友在操场围坐成一圈,每人手里有数量不等的糖果,小朋友们可以向左右传递,请问至少需要传递多少颗糖果才能使得所有小朋友手里的糖果数一样。

Input
Input a positive integer n in the first line, which means the number of children. (1≤n≤1000000)

In the next n lines, each line contains an integer, which represents the number of candies in each child's hand at the beginning.
Output
an integer, representing the minimum number of candies passed. (Data guaranteed to have solutions)
Input sample
4
1
2
5
4
Output sample
4

Ideas:

I thought it was a water problem, and then I enumerated violently without looking at the data points, and thenInsert picture description here

Correct answer:

Table AC greedy thinking, first find the total/n (number), store the result in an array using similar prefixes and ideas, and find the median after sorting, and then subtract each number from the median.

Code

#include<bits/stdc++.h>
using namespace std;
long long a[1000100],x[1000100];
long long mid,ans,n,sum;
int main()
{
    
    
	ios::sync_with_stdio(false);
	cin>>n;
	for(int i=1;i<=n;i++)
	{
    
    
		cin>>a[i];
		sum+=a[i];
	}
	sum/=n;
	for(int i=1;i<=n;i++)
		x[i]=x[i-1]-a[i]+sum;
	sort(x+1,x+1+n);
	mid=x[(n+1)/2];
	for(int i=1;i<=n;i++)
		ans+=abs(x[i]-mid);
	cout<<ans;
	return 0;
}

This is the first time this Konjac has written a solution to a problem, so please take care of me

Guess you like

Origin blog.csdn.net/SSL_pqk/article/details/113736201