0%

Max Median

Max Median

time limit per test 2 seconds

memory limit test 256 megabytes

Articles

You are a given an array aa of length nn. Find a subarray a[l..r]a[l..r] with length at least kk with the largest median.

A median in an array of length nn is an element which occupies position number n+12⌊ \frac {n+1}{2}⌋ after we sort the elements in non-decreasing order. For example: median([1,2,3,4])=2median([1,2,3,4])=2, median([3,2,1])=2median([3,2,1])=2, median([2,1,2,1])=1median([2,1,2,1])=1.

Subarray a[l..r]a[l..r] is a contiguous part of the array aa, i.e.i. e. the array al,al+1,,ara_l,a_{l+1},…,a_rfor some 1lrn1≤l≤r≤n, its length is rl+1r−l+1.

Input

The first line contains two integers nn and kk (1kn21051≤k≤n≤2⋅10^5).

The second line contains nn integers a1,a2,,ana_1,a_2,…,a_n (1ain1≤ai≤n).

Output

Output one integer mm — the maximum median you can get.

Example

input

1
2
5 3
1 2 3 2 1

output

1
2

input

1
2
4 2
1 2 3 4

output

1
3

Note
In the first example all the possible subarrays are [1..3],[1..4],[1..5],[2..4],[2..5][1..3], [1..4], [1..5], [2..4], [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])=3median([3..4])=3.

思路

首先二分一个中位数 xx,然后思考一个区间 [l,r][l,r] 的中位数不小于 xx 要满足什么条件?

记录一个前缀数组 p[i]p[i] 表示在前 ii 个元素中小于 xx 的个数,所以若 r(l1)>2(p[r]p[l1])r-(l-1) > 2*(p[r] - p[l-1]) ,则该区间 [l,r][l,r] 中位数不小于 xx

最后从一个区间 [l,r][l, r] 推到所有区间,即所有满足 r2p[r]>(l1)2p[l1]r-2*p[r] > (l-1) - 2*p[l-1] 关系的区间,它们的中位数都不小于 xx

由于频繁的插入和前缀求和,所以我们选择树状数组进行优化。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include<bits/stdc++.h>

using namespace std;

const int maxn = 1e6+1;
int n, k, a[maxn], b[maxn], c[maxn];
int tree[maxn];

void add(int x) {
for(int i = x; i <= 2*n; i += i&-i) {
tree[i] ++;
}
}

int sum(int x) {
int ans = 0;
for(int i = x; i; i -= i&-i) {
ans += tree[i];
}
return ans;
}

bool check(int x) {
for(int i = 1; i <= 2*n; ++ i) tree[i] = 0;
c[0] = n+1;
for(int i = 1; i <= n; ++ i) {
b[i] = b[i-1] + (a[i] < x);
c[i] = i - 2*b[i] + n+1;
if (i >= k) add(c[i-k]);
if (sum(c[i]-1)) return true;
}
return false;
}

int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin >> n >> k;
for(int i = 1; i <= n; ++ i) {
cin >> a[i];
}
int l = 1, r = n+1;
while(l < r) {
int mid = (l+r) >> 1;
if (check(mid)) l = mid+1;
else r = mid;
}
cout << l-1 << "\n";
return 0;
}
-------------本文结束感谢您的阅读-------------