Max Median 二分答案

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值