CodeforcesAug 08, 2025

Reach Median

Hazrat Ali

Codeforces

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 (1n210511s10) — the length of the array and the required value of median.

The second line contains n integers a1,a2,,an (1ai10) — 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
3 8
6 5 8
Output
2
Input
7 20
21 15 12 11 20 19 12
Output
6

Solution

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

int main()
{
    int n, s;
    cin >> n >> s;
    vector<long long> a(n);
    for (int i = 0; i < n; i++)
    {
        cin >> a[i];
    }
    long long ans = 0;
    sort(a.begin(), a.end());
    auto lower = lower_bound(a.begin(), a.end(), s);
    int j = lower - a.begin();
    if (j > n / 2)
    {
        for (int i = n / 2; i < j; i++)
        {
            ans += s - a[i];
        }
    }
    else if (j < n / 2)
    {
        for (int i = j; i < n / 2 + 1; i++)
        {
            ans += a[i] - s;
        }
    }
    else
    {
        ans += abs(a[j] - s);
    }
    cout << ans << endl;
    return 0;
}





Comments