B. Reach Median (cf 1037 B) - Manthan, Codefest 18 (rated, Div. 1 + Div. 2)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/OscaronMar/article/details/82353595

B. 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 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≤10^9) — 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.
Output
In a single line output the minimum number of operations to make the median being equal to s
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, 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.
题目:Reach Median

题意:给出一个长度为n的序列和一个整数k,求最少需要多少次操作可以把序列的中位数变成k。一次操作定义为将序列中的任意一个数+1或-1。

思路:
经过观察可以知道,不改变序列元素之间的相对大小是更优的选择。
先对序列进行排序。
如果当前中位数小于k,那么就把它加到k,为了保证序列的相对大小不变,需要把它后面小于k的数都加到k。大于k时同理。

代码:

#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define maxn 200000

int n,k;
int a[maxn+5];

int main() {
    scanf("%d%d",&n,&k);
    for(int i=1;i<=n;i++) {
        scanf("%d",&a[i]);
    }
    sort(a+1,a+n+1);
    int mid=(n+1)/2;
    if(a[mid]==k) {
        printf("0");
        return 0;
    } else if(a[mid]<k) {
        ll ans=0;
        for(int i=mid;i<=n;i++) {
            if(a[i]<k) ans+=k-a[i]; 
        }
        printf("%I64d",ans);
    } else if(a[mid]>k) {
        ll ans=0;
        for(int i=1;i<=mid;i++) {
            if(a[i]>k) ans+=a[i]-k; 
        }
        printf("%I64d",ans);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/OscaronMar/article/details/82353595