C. Maximum Median
You are given an array a of n integers, where n is odd. You can make the following operation with it:
Choose one of the elements of the array (for example ai) and increase it by 1 (that is, replace it with ai+1).
You want to make the median of the array the largest possible using at most k 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] is 3.
Input
The first line contains two integers n and k (1≤n≤2⋅105, n is odd, 1≤k≤109) — the number of elements in the array and the largest number of operations you can make.
The second line contains n integers a1,a2,…,an (1≤ai≤109).
Output
Print a single integer — the maximum possible median after the operations.
Examples
inputCopy
3 2
1 3 5
outputCopy
5
inputCopy
5 5
1 2 1 1 1
outputCopy
3
inputCopy
7 7
4 1 2 4 3 4 4
outputCopy
5
Note
In the first example, you can increase the second element twice. Than array will be [1,5,5] and it’s median is 5.
In the second example, it is optimal to increase the second number and than increase third and fifth. This way the answer is 3.
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] and the median will be 5.
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;
typedef long long ll;
ll a[N];
ll n,k,l,r,ans;
bool C(ll x){
ll res=k;
for(int i=n>>1;i<n;++i){
if(a[i]>=x)return 1;
else res-=x-a[i];
if(res<0)return 0;
}
return 1;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>n>>k;
for(int i=0;i<n;++i)cin>>a[i],r=max(a[i],r);
sort(a,a+n);
l=a[n>>1],r+=k;
while(l<=r){
ll mid=(l+r)>>1;
if(C(mid))ans=mid,l=mid+1;
else r=mid-1;
}
cout<<ans;
return 0;
}

探讨了如何通过有限次数的操作使奇数长度数组的中位数最大化的算法问题,利用二分查找和排序技巧,提供了详细的代码实现及示例说明。
304

被折叠的 条评论
为什么被折叠?



