1037B - Reach Median(模拟)

1037B - Reach Median

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个数与一个s,使得问通过对n个数中的任意数进行加一或者减一操作最少多少次之后可以使得这n个数的中位数为s。

思路:简单模拟,不解释。

#include<cstdio>
#include<iostream>
#include<algorithm>
#define lowbit(x) x&(-x)
using namespace std;
const int size=1e6+5;
int c[size];
int main()
{
	int n,s;
	scanf("%d%d",&n,&s);
	for(int i=1;i<=n;i++)
	{
		scanf("%d",&c[i]);
	}
	sort(c+1,c+1+n);
	int loc=lower_bound(c+1,c+1+n,s)-c;
	int l=loc-1;
	int r=n-l;
	if(c[loc]==s) --r,loc++;
	int loop=abs(r-l);
	long long ans=0;
	int len=loop/2+(loop%2!=0);
	if(l==r) ans=0;
	else if(l<r)
	{
		for(int i=loc;i<=loc+len-1;i++)
		{
			ans+=(c[i]-s);
		}
	}
	else
	{
		for(int i=l-len+1;i<=l;i++)
		{
			ans+=(s-c[i]);
		}
	}
	cout<<ans<<endl;
}

猜你喜欢

转载自blog.csdn.net/baiyifeifei/article/details/82354554