练习cf1946A. Median of an Array

题目如下
A. Median of an Array
time limit per test1 second
memory limit per test256 megabytes
You are given an array 𝑎 of 𝑛 integers.

The median of an array 𝑞1,𝑞2,…,𝑞𝑘 is the number 𝑝⌈𝑘2⌉, where 𝑝 is the array 𝑞 sorted in non-decreasing order. For example, the median of the array [9,5,1,2,6] is 5, as in the sorted array [1,2,5,6,9], the number at index ⌈52⌉=3 is 5, and the median of the array [9,2,8,3] is 3, as in the sorted array [2,3,8,9], the number at index ⌈42⌉=2 is 3.

You are allowed to choose an integer 𝑖 (1≤𝑖≤𝑛) and increase 𝑎𝑖 by 1 in one operation.

Your task is to find the minimum number of operations required to increase the median of the array.

Note that the array 𝑎 may not necessarily contain distinct numbers.

Input
Each test consists of multiple test cases. The first line contains a single integer 𝑡 (1≤𝑡≤104) — the number of test cases. Then follows the description of the test cases.

The first line of each test case contains a single integer 𝑛 (1≤𝑛≤105) — the length of the array 𝑎.

The second line of each test case contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (1≤𝑎𝑖≤109) — the array 𝑎.

It is guaranteed that the sum of the values of 𝑛 over all test cases does not exceed 2⋅105.

Output
For each test case, output a single integer — the minimum number of operations required to increase the median of the array.
题目大意
现有未排序的数组a,按照升序排序后中位数为a[n/2],现在要对中位数进行加一操作,要保持当前中位数位置不变,至少要对其他数进行几次加一操作才能实现,输出加一操作的总次数。

题目分析
对当前中位数进行加一操作,且要保持位置不变,那么只要保证加一后的中午的中位数,至少小于等于后面的任意一个元素即可。
若排序后吗满足当前中位数小于后一位,直接对中位数加一即可;

完整代码

点击查看代码
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(){
    int t;
    scanf("%d", &t);
    while(t--){
        int n;
        scanf("%d", &n);
        vector<long long> a;
        for(int i = 0; i < n; i++){
            long long num;
            cin >> num;
            a.push_back(num);
        }
        sort(a.begin(),a.end());
        int index = (n % 2 == 0) ? n / 2 - 1 : n / 2;
        long long mid = a[index];
        int cnt = 0;
        for(int i = index; i < n; i++){
            if(a[i] == mid){
                cnt++;
            }else{
                break;
            }
        }
        printf("%d\n", cnt);
    }
    return 0;
}
posted @ 2025-07-17 19:21  sirro1uta  阅读(16)  评论(0)    收藏  举报