【題解】CF1175C:Electrification

ModestCoder_發表於2020-10-19

原題傳送門
二分最優值,然後 O ( n ) O(n) O(n)驗證
對於每個 i i i,就是看 [ i , i + k ] [i,i+k] [i,i+k]這段區間能不能達到這個最優值
就是 [ a i + k − a i + 1 2 ] < = m i d [\frac{a_{i+k}-a_i+1}{2}]<=mid [2ai+kai+1]<=mid,可行的話,答案就是 [ a i + k + a i + 1 2 ] [\frac{a_{i+k}+a_i+1}{2}] [2ai+k+ai+1]

Code:

#include <bits/stdc++.h>
#define maxn 200010
using namespace std;
int a[maxn], n, k;

inline int read(){
	int s = 0, w = 1;
	char c = getchar();
	for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
	for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
	return s * w;
}

int main(){
	int T = read();
	while (T--){
		n = read(), k = read();
		for (int i = 1; i <= n; ++i) a[i] = read();
		int l = 0, r = a[n], ans;
		while (l <= r){
			int mid = (l + r) >> 1, flag = 0;
			for (int i = 1; i + k <= n; ++i)
				if ((a[i + k] - a[i] + 1) / 2 <= mid){
					flag = 1, ans = (a[i + k] + a[i]) >> 1;
					break;
				}
			if (flag) r = mid - 1; else l = mid + 1;
		}
		printf("%d\n", ans);
	}
	return 0;
}