C. Maximum Median
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given an array aa of nn integers, where nn is odd. You can make the following operation with it:
- Choose one of the elements of the array (for example aiai) and increase it by 11 (that is, replace it with ai+1ai+1).
You want to make the median of the array the largest possible using at most kk operations.
The median of the odd-sized array is the middle element after the array is sorted in non-decreasing order. For example, the median of the array [1,5,2,3,5][1,5,2,3,5] is 33.
Input
The first line contains two integers nn and kk (1≤n≤2⋅1051≤n≤2⋅105, nn is odd, 1≤k≤1091≤k≤109) — the number of elements in the array and the largest number of operations you can make.
The second line contains nn integers a1,a2,…,ana1,a2,…,an (1≤ai≤1091≤ai≤109).
Output
Print a single integer — the maximum possible median after the operations.
Examples
input
Copy
3 2 1 3 5
output
Copy
5
input
Copy
5 5 1 2 1 1 1
output
Copy
3
input
Copy
7 7 4 1 2 4 3 4 4
output
Copy
5
Note
In the first example, you can increase the second element twice. Than array will be [1,5,5][1,5,5] and it's median is 55.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 33.
In the third example, you can make four operations: increase first, fourth, sixth, seventh element. This way the array will be [5,1,2,5,3,5,5][5,1,2,5,3,5,5] and the median will be 55.
二分中位数,不过check 需要注意一下,只需要考虑中位数所在位置之后的数,不用管他之前的数。
假如说数列排序后序列为1 7 10 10 10时,如果我们当前判断的mid为6,那么我们需要return 1来让mid值更大,如果我们判断了它和a[n/2]的关系,直接return mid<a[n/2],那么mid会更小。
我们只用判断中位数和后面的关系,它既然>=了后面的,必然会大于前面的。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int maxn=200000+66;
const ll mod=1e9+7;
ll n,m;//m次操作
ll a[maxn];
bool check(ll mid)
{
//看他左边比它小的有多少个
ll s1=0;
for(int i=n/2+1;i<=n;i++)
{
if(a[i]<mid)s1+=mid-a[i];
}
return s1<=m;
}
int main()
{
scanf("%lld %lld",&n,&m);
for(int i=1; i<=n; i++)
{
scanf("%lld",&a[i]);
}
sort(a+1,a+n+1);
ll l=1,r=3e9;
while(l<r)//求最大的中位数
{
ll mid=(l+r+1)/2;
if(check(mid))
{
l=mid;
}
else
{
r=mid-1;
}
}
printf("%lld\n",l);
}