Codeforce 1037B Reach Median【2018.9.2混合场】No.11

Reach Median

传送
You are given an array a of n integers and an integer s. It is guaranteed that
n 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 s.
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,8 is equal to 6, since if we sort this array we will get 5,6,8, and 6 is located on the middle position.

Input

The first line contains two integers n and s (1≤n≤2⋅105−1, 1≤s≤109) — the length of the array and the required value of median.
The second line contains n integers a1,a2,…,an (1≤ai≤109) — the elements of the array a.
It is guaranteed that n is odd.

Examples

input

3 8
6 5 8

output

2

input

7 20
21 15 12 11 20 19 12

output

6

Note

In the first sample, 6 can be increased twice. The array will transform to 8,5,8, which becomes 5,8,8 after sorting, hence the median is equal to 8.
In the second sample, 19 can be increased once and 15 can be increased five times. The array will become equal to 21,20,12,11,20,20,12. If we sort this array we get 11,12,12,20,20,20,21, this way the median is 20.


题目大意:

有n个数,每次可以对一个数进行+1或-1的操作,问最少需要几次才能使得该组数的中位数等于s

做法:

540B school mark 有点类似
贪心:尽可能的改变离中位数近的数
因为只有两种情况:全部加分操作或者全部减分操作
所以分离大于等于s的和小于s的数,再分别排序
判断情况:
1.如果需要加,就从小于s的数组中,从大到小加
2.如果需要减,就从大于s的数组中,从小到大减

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int n,s;
int a[200010],b[200010],c[200010];
int num1,num2,mid;
long long ans;
int read(){
int res=0;char ch;
while(!isdigit(ch)) ch=getchar();
while(isdigit(ch)) res=res*10+ch-'0',ch=getchar();
return res;
}
bool cmp(int x,int y){
return x>y;
}
int main(){
n=read();s=read();
mid=(n/2)+1;
for(int i=1;i<=n;i++){
a[i]=read();
if(a[i]>=s){
num1++;
b[num1]=a[i];
}
else{
num2++;
c[num2]=a[i];
}
}
sort(b+1,b+1+num1);
sort(c+1,c+1+num2,cmp);
if(num1>=mid){
int t=num1-mid+1;
for(int i=1;i<=t;i++){
ans+=b[i]-s;
}
}
else{
int t=num2-mid+1;
for(int i=1;i<=t;i++){
ans+=s-c[i];
}
}
cout<<ans<<endl;
}

Powered by Hexo and Hexo-theme-hiker

Copyright © 2013 - 2018 Gilgamesh All Rights Reserved.

UV : | PV :