1. 程式人生 > >NewCoder #提高組 Contest 1 A. 中位數

NewCoder #提高組 Contest 1 A. 中位數

題意

求序列中長度>=len的連續子序列的中位數的最大值

題解

二分,列舉答案並檢查是否可行

除錯記錄

#include <cstdio>
#include <algorithm>
#define INF 0x3f3f3f3f
#define maxn 100005

using namespace std;

int n, len, a[maxn], sum[maxn];

bool check(int mid){
	sum[0] = 0;
	for (int i = 1; i <= n; i++)
		sum[i] = sum[
i - 1] + ((a[i] >= mid) ? 1 : -1); int Min = INF; for (int i = len; i <= n; i++){ Min = min(Min, sum[i - len]); if (sum[i] - Min > 0) return true; } return false; } int main(){ scanf("%d%d", &n, &len); for (int i = 1; i <= n; i++) scanf("%d", &a[i]); int l = 1,
r = INF, ans; while (l <= r){ int mid = (l + r) >> 1; if (check(mid)) l = mid + 1, ans = mid; else r = mid - 1; } printf("%d\n", ans); return 0; }