\(题意:给定长度为n的序列,找到一个子序列长度\ge k的a[l..r],使中位数最大\)
- \(二分答案\)
- \(将大于等于x的数标记为1,否者标记为-1,求一遍前缀和可快速确定x能否为这一段的中位数\)
- \(因为长度不确定所以再记录前缀的最小值,那么若满足s[i]-ms[i-k]>=1\\ 表示可以找到一段以i为右端点的序列,它的长度\ge k\)
- \(综上,去找满足条件的最大值\)
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define ull unsigned long long
#define pb push_back
#define PII pair<int, int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 2e5 + 7;
int n, k;
int a[N];
bool check(int x) {
vector<int> s(n + 1), ms(n + 1);
for (int i = 1; i <= n; ++i) s[i] = a[i] >= x ? 1 : -1;
for (int i = 1; i <= n; ++i) {
s[i] += s[i - 1];
ms[i] = min(ms[i - 1], s[i]);
}
for (int i = k; i <= n; ++i)
if (s[i] - ms[i - k] >= 1) return true;
return false;
}
int main() {
IO;
cin >> n >> k;
for (int i = 1; i <= n; ++i) cin >> a[i];
int l = 1, r = 2e5;
while (l < r) {
int mid = l + r + 1 >> 1;
if (check(mid)) l = mid;
else r = mid - 1;
}
cout << l << '\n';
return 0;
}