给出一个数组,长度是n,对于区间,长度至少为k
求最大区间中位数
传送门
用二分去求。
对于某个数字判断是否是中位数:
首先肯定的是大于等于中位数数的数的数字比小于中位数的数字要来的大。
那么就求出前缀和
如果这个数字比中位数小,那么权值就是-1,否则就是1
然后只需要去判断是否存在一个区间长度大于等于k的,并且该区间长度的权值和大于0
遍历数组,假设我当前区间是以i为右区间,然后在i - k之前找到最小值,如果说我前缀和-最小值大于0,那么答案就是存在一个区间。
#include <bits/stdc++.h>
#define ll long long
#define ld long double
#define CASE int Kase = 0; cin >> Kase; for(int kase = 1; kase <= Kase; kase++)
using namespace std;
template<typename T = long long> inline T read() {
T s = 0, f = 1; char ch = getchar();
while(!isdigit(ch)) {if(ch == '-') f = -1; ch = getchar();}
while(isdigit(ch)) {s = (s << 3) + (s << 1) + ch - 48; ch = getchar();}
return s * f;
}
#ifdef ONLINE_JUDGE
#define qaq(...) ;
#define qwq(c) ;
#else
#define qwq(a, b) for_each(a, b, [=](int x){cerr << x << " ";}), cerr << std::endl
template <typename... T> void qaq(const T &...args) {
auto &os = std::cerr;
(void)(int[]){(os << args << " ", 0)...};
os << std::endl;
}
#endif
const int N = 2e5 + 5, M = 1e6 + 5, MOD = 1e9 + 7, CM = 998244353, INF = 0x3f3f3f3f; const ll linf = 0x7f7f7f7f7f7f7f7f;
int a[N];
int pre[N];
bool check(int mid, int n, int k) {
for(int i = 1; i <= n; i++) {
pre[i] = pre[i - 1] + (a[i] >= mid ? 1 : -1);
}
int mi = INF, mx = 0;
for(int i = k; i <= n; i++) { // 查看是否存在一个区间满足前缀和大于0,也就是说,x > y
mi = min(mi, pre[i - k]);
mx = max(mx, pre[i] - mi);
}
return mx > 0;
}
void solve(int kase){
int n = read(), k = read();
for(int i = 1; i <= n; i++) a[i] = read();
int l = 1, r = INF;
for(int i = 1; i <= 100; i++) {
int mid = (l + r) >> 1;
if(check(mid, n, k)) l = mid;
else r = mid;
}
printf("%d\n", l);
}
/*
大于等于a的数的个数x
小于a的数的个数y
那么一定存在x > y
n是奇数的时候:
x = y + 1
n是偶数的时候:
x = y + 2
想法就是去判断十分存在一个区间,满足前缀和大于0
*/
const bool ISFILE = 0, DUO = 0;
int main(){
clock_t start, finish; start = clock();
if(ISFILE) freopen("/Users/i/Desktop/practice/in.txt", "r", stdin);
if(DUO) {CASE solve(kase);} else solve(1);
finish = clock();
qaq("\nTime:", (double)(finish - start) / CLOCKS_PER_SEC * 1000, "ms\n");
return 0;
}