A.MedianofanArrayA. Median of an ArrayA.MedianofanArray
timelimitpertest:1secondtime limit per test: 1 secondtimelimitpertest:1second
memorylimitpertest:256megabytesmemory limit per test: 256 megabytesmemorylimitpertest:256megabytes
input:standardinputinput: standard inputinput:standardinput
output:standardoutputoutput: standard outputoutput:standardoutput

给你一个由 nnn 个整数组成的数组 aaa

数组 q1,q2,…,qkq_1, q_2, \ldots, q_kq1,q2,,qk 的中位数是 p⌈k2⌉p_{\lceil \frac{k}{2} \rceil}p2k ,其中 ppp 是按非递减顺序排序的数组 qqq 。例如,数组 [9,5,1,2,6][9, 5, 1, 2, 6][9,5,1,2,6] 的中位数是 555 ,如在排序数组 [1,2,5,6,9][1, 2, 5, 6, 9][1,2,5,6,9] 中,索引 ⌈52⌉=3\lceil \frac{5}{2} \rceil = 325=3 处的数字是 555 ;数组 [9,2,8,3][9, 2, 8, 3][9,2,8,3] 的中位数是 333 ,如在排序数组 [2,3,8,9][2, 3, 8, 9][2,3,8,9] 中,索引 ⌈42⌉=2\lceil \frac{4}{2} \rceil = 224=2 处的数字是 333

您可以选择一个整数 iii ( 1≤i≤n1 \le i \le n1in ),并在一次操作中将 aia_iai 增加 111

你的任务是找出增加数组中位数所需的最少操作次数。

注意数组 aaa 不一定包含不同的数。

输入

每个测试由多个测试用例组成。第一行包含一个整数 ttt ( 1≤t≤1041 \le t \le 10^41t104 ) - 测试用例的数量。然后是测试用例的描述。

每个测试用例的第一行包含一个整数 nnn ( 1≤n≤1051 \le n \le 10^51n105 ) - 数组 aaa 的长度。

每个测试用例的第二行包含 nnn 个整数 a1,a2,…,ana_1, a_2, \ldots, a_na1,a2,,an ( 1≤ai≤1091 \le a_i \le 10^91ai109 ) - 数组 aaa

保证所有测试用例中 nnn 的值之和不超过 2⋅1052 \cdot 10^52105

输出

对于每个测试用例,输出一个整数 - 增加数组中位数所需的最少操作数。


在排序之后,位于 ⌈n2⌉\lceil\frac{n}{2}\rceil2n 下标处的数就被认为是中位数,暂时使这个下标为 ppp ,如果想要改变中位数的数值,那么就要使得 ppp 下标之后的数都满足大于或者等于 a[p]a[p]a[p] ,因为只有这样才能够满足数组的有序顺序不会改变。

所以直接先取出中位下标然后取扫后面有多少数和中位数相等。
不用管大于中位数的数是因为,就算中位数加 111 了之后他们也是大于等于中位数,不会影响整体顺序。

代码:

#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
const int N = 1e5+10;

int a[N];

void solve(){
	int n;cin >> n;
	for(int i = 1;i <= n;i++)cin >> a[i];

	int mid = (n+1)/2;//取出中位下标

	int res = 1;//先提前加上中位数本身应该加的1

	for(int i = mid + 1;i <= n;i++){
		if(a[i] == a[mid])res++;
	}
	cout << res << endl;
	return;
}

int main(){
	int t;cin >> t;

	while(t--)
		solve();

	return 0;
}
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐