time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given an array aa of nn integers and an integer ss. It is guaranteed that nn is odd.
In one operation you can either increase or decrease any single element by one. Calculate the minimum number of operations required to make the median of the array being equal to ss.
The median of the array with odd length is the value of the element which is located on the middle position after the array is sorted. For example, the median of the array 6,5,86,5,8 is equal to 66, since if we sort this array we will get 5,6,85,6,8, and 66 is located on the middle position.
Input
The first line contains two integers nn and ss (1≤n≤2⋅105−11≤n≤2⋅105−1, 1≤s≤1091≤s≤109) — the length of the array and the required value of median.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109) — the elements of the array aa.
It is guaranteed that nn is odd.
Output
In a single line output the minimum number of operations to make the median being equal to ss.
Examples
input
Copy
3 8 6 5 8
output
Copy
2
input
Copy
7 20 21 15 12 11 20 19 12
output
Copy
6
Note
In the first sample, 66 can be increased twice. The array will transform to 8,5,88,5,8, which becomes 5,8,85,8,8 after sorting, hence the median is equal to 88.
In the second sample, 1919 can be increased once and 1515 can be increased five times. The array will become equal to 21,20,12,11,20,20,1221,20,12,11,20,20,12. If we sort this array we get 11,12,12,20,20,20,2111,12,12,20,20,20,21, this way the median is 2020.
题意是给了n个数,可以对这n个数进行加一减一的操作,问最少需要操作多少次可以让这n个数的中位数等于m。
首先我们对其进行排序,拿第二个样例来看,排完序后是11 12 12 15 19 20 21,想让中位数是20,就需要把15加5,19加1就好了,所以我们可以由此知道,对于中位数右边的数如果小于m的话就让它加到m,大于m的数对其进行操作的话是没有意义的,同理,中位数左边的数则是大于m的让它减到m就好了。
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
long long int n,m;
long long int a[200011];
cin>>n>>m;
for(int i=0; i<n; i++)
{
cin>>a[i];
}
sort(a,a+n);
long long int ans=0;
ans=abs(a[n/2]-m);
for(int i=n/2+1; i<n; i++)
if(a[i]<m)
ans+=m-a[i];
for(int i=0; i<n/2; i++)
if(a[i]>m)ans+=a[i]-m;
cout<<ans<<endl;
return 0;
}