CodeForces 655C Enduring Exodus (三分)

题意:n个房间,k头牛和1个人,有的房间已经被占了,要求选择k+1个房间,使得人住的房间离最远的牛距离最短。

题解:三分
题目给出01字符串,只考虑距离,先把0的编号提取到单独的数组中,由于人到牛的距离从左到右呈二次函数,暴力所有段,处理极值选择三分。

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define ll long long
using namespace std;
const int maxn = 1e5 + 10;
int n, k;
char s[maxn];
vector<int> v;
int main() {
	scanf("%d%d%s", &n, &k, s + 1);
	for (int i = 1; i <= n; i++) {
		if (s[i] == '0') v.push_back(i);
	}
	int len = v.size(), ans = maxn;
	for (int i = 1; i <= len - k; i++) {
		int l = i - 1, r = i + k - 1, mid, midmid, temp;
		while (l + 1 < r) {
			mid = (l + r) >> 1;
			midmid = (mid + r) >> 1;
			int x = max(v[mid] - v[i - 1], v[i + k - 1] - v[mid]);
			int y = max(v[midmid] - v[i - 1], v[i + k - 1] - v[midmid]);
			if (x >= y) l = mid;
			else r = midmid;
		}
		ans = min(ans, max(v[l] - v[i - 1], v[i + k - 1] - v[l]));
	}
	printf("%d\n", ans);
	return 0;
}

你可能感兴趣的:(#,二分,三分)