bzoj 1052 [HAOI2007]覆盖问题 二分答案+贪心

题面

题目传送门

解法

显然可以二分答案

问题就转化为如何检查答案的合法性

考虑这样一个贪心

显然,可以用一个矩形将剩下所有点覆盖,考虑将前两个正方形放在这个矩形的哪四个角,枚举一下

最后看剩下的点能否用一个正方形覆盖就可以了

贪心的复杂度是\(O(n)\)的,因为每一个点最多只会被覆盖一次

时间复杂度:\(O(n\ log\ 10^9)\)

代码

#include <bits/stdc++.h>
#define inf 1e9
#define N 20010
using namespace std;
template <typename node> void chkmax(node &x, node y) {x = max(x, y);}
template <typename node> void chkmin(node &x, node y) {x = min(x, y);}
template <typename node> void read(node &x) {
	x = 0; int f = 1; char c = getchar();
	while (!isdigit(c)) {if (c == '-') f = -1; c = getchar();}
	while (isdigit(c)) x = x * 10 + c - '0', c = getchar(); x *= f;
}
struct Node {
	int x, y;
} a[N], b[N], c[N];
int n, tot;
void del(int x1, int x2, int y1, int y2) {
	int tmp = 0;
	for (int i = 1; i <= tot; i++)
		if (x1 > b[i].x || b[i].x > x2 || y1 > b[i].y || b[i].y > y2)
			c[++tmp] = b[i];
	tot = tmp;
	for (int i = 1; i <= tmp; i++) b[i] = c[i];
}
void solve(int key, int mid) {
	int x1 = inf, y1 = inf, x2 = -inf, y2 = -inf;
	for (int i = 1; i <= tot; i++) {
		chkmin(x1, b[i].x), chkmax(x2, b[i].x);
		chkmin(y1, b[i].y), chkmax(y2, b[i].y);
	}
	if (key == 1) del(x1, x1 + mid, y1, y1 + mid);
	if (key == 2) del(x2 - mid, x2, y1, y1 + mid);
	if (key == 3) del(x1, x1 + mid, y2 - mid, y2);
	if (key == 4) del(x2 - mid, x2, y2 - mid, y2);
}
bool check(int mid) {
	for (int x = 1; x <= 4; x++)
		for (int y = 1; y <= 4; y++) {
			for (int i = 1; i <= n; i++) b[i] = a[i];
			tot = n, solve(x, mid), solve(y, mid);
			int x1 = inf, y1 = inf, x2 = -inf, y2 = -inf;
			for (int i = 1; i <= tot; i++) {
				chkmin(x1, b[i].x), chkmax(x2, b[i].x); 
				chkmin(y1, b[i].y), chkmax(y2, b[i].y);
			}
			if (x2 - x1 <= mid && y2 - y1 <= mid) return true;
		}
	return false;
}
int main() {
	read(n);
	for (int i = 1; i <= n; i++)
		read(a[i].x), read(a[i].y);
	int l = 0, r = 1e9, ans = 0;
	while (l <= r) {
		int mid = (l + r) >> 1;
		if (check(mid)) ans = mid, r = mid - 1;
			else l = mid + 1;
	}
	cout << ans << "\n";
	return 0;
}

posted @ 2018-08-14 18:26  谜のNOIP  阅读(30)  评论(0编辑  收藏