Candy pass math problem

Candy pass math problem

answer

Find the minimum distance from a point to all known points. When the number is odd, the middle point is even, and the middle two points are acceptable.
Because the distance to the two ends of the line segment and the shortest point must be on the line segment; sort the n points from small to large, the unselected points must be evenly distributed on both sides of the selected point to ensure that the selected point The point can be on the line segment formed by each pair of points (the two points are on the left and right of the point respectively);

#include<iostream>
#include<algorithm> 
using namespace std;

#define  ll  long long

int n;

ll sum;
ll mid;
ll ave;
ll ans;
int a[1000005];
int c[1000005];


int main()
{
    
    
	cin>>n;
	for(int i=1;i<=n;i++)
	{
    
    
		cin>>a[i];
		sum+=a[i];		
	}
	
	ave=sum/n;
	c[0]=0;
	
	for(int i=1;i<n;i++)
	{
    
    
		c[i]=c[i-1]+a[i]-ave;
	}
	
	sort(c,c+n);
	mid=c[n/2];
	
	for(int i=0;i<n;i++)
	{
    
    
		ans+=abs(c[i]-mid);
	}
	
	printf("%lld",ans);
	
	
	return 0;
}
 

Guess you like

Origin blog.csdn.net/weixin_45448563/article/details/113622820