Description
You are a given an array �a of length �n. Find a subarray �[�..�]a[l..r] with length at least �k with the largest median.
A median in an array of length �n is an element which occupies position number ⌊�+12⌋⌊2n+1⌋ after we sort the elements in non-decreasing order. For example: ������([1,2,3,4])=2median([1,2,3,4])=2, ������([3,2,1])=2median([3,2,1])=2, ������([2,1,2,1])=1median([2,1,2,1])=1.
Subarray �[�..�]a[l..r] is a contiguous part of the array �a, i. e. the array ��,��+1,…,��al,al+1,…,ar for some 1≤�≤�≤�1≤l≤r≤n, its length is �−�+1r−l+1.
The first line contains two integers �n and �k (1≤�≤�≤2⋅1051≤k≤n≤2⋅105).
The second line contains �n integers �1,�2,…,��a1,a2,…,an (1≤��≤�1≤ai≤n).
Output one integer �m — the maximum median you can get.
Input
The first line contains two integers �n and �k (1≤�≤�≤2⋅1051≤k≤n≤2⋅105).
The second line contains �n integers �1,�2,…,��a1,a2,…,an (1≤��≤�1≤ai≤n).
Output
Output one integer �m — the maximum median you can get.
Samples
输入数据 1
5 3
1 2 3 2 1
输出数据 1
2
输入数据 2
4 2
1 2 3 4
输出数据 2
3
Note
In the first example all the possible subarrays are [1..3][1..3], [1..4][1..4], [1..5][1..5], [2..4][2..4], [2..5][2..5] and [3..5][3..5] and the median for all of them is 22, so the maximum possible median is 22 too.
In the second example median([3..4])=3.
代码如下:
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+5;
int n,k,a[N]={},b[N]={},c[N];
bool fun(int x){
for(int i=1;i<=n;i++){
if(a[i]>=x) b[i]=1;
else b[i]=-1;
}
for(int i=1;i<=n;i++){
b[i]+=b[i-1];
c[i]=min(b[i],c[i-1]);
if(i>=k&&b[i]-c[i-k]>=1) return 1;
}
return 0;
}
int main(){
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i];
int l=1,r=n;
while(r>l){
int mid=l+r+1>>1;
if(fun(mid)==1) l=mid;
else r=mid-1;
}
cout<<l;
return 0;
}