题意:给出n个点,定义两个点能相互到达当且仅当一个节点能够通过曼哈段距离到达另外一个节点,而且仅当遇到其他点才能拐弯。问图中是否所有节点都能相互到达。
线段树
题解:首先对所有点优先按 x 坐标进行排序,每次对于当前状态,我们都保证在搜到的 x 坐标左边的所有点满足两两之间相互连通,然后对于每一次新加进来的 x ,从下至上扫描每个点,并且找到对应 y 坐标最右边的点,那么该节点满足于左边节点满足连通性,必须要它于它上下的节点向左找的第一个节点中不存在其他节点(比较拗口,如图),然后对于最上面的还要判断上面的不存在其他节点
如图 黄色区域中不能出现其他点,不然 i j k必定有节点不能到达。于是对于y轴就可以用线段树来维护,记录区间最大的x值,如果超过了设立的边界,那么就代表有点进入黄色区域,直接为NO,否则为YES
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int maxn = 600000;
struct Node {
int x, y;
bool operator<(Node &other) {
if (x < other.x) return true;
if (x > other.x) return false;
if (y < other.y) return true;
return false;
}
}a[maxn], queue[maxn];
int n, x, y, tree[6*maxn], maxx, init, t, t1, last[maxn], tot;
bool flag;
void insert(int x, int l, int r, int index, int val) {
if (l == r) {
tree[x] = val;
return;
}
int mid = (l+r)/2;
if (index <= mid) insert(x*2, l, mid, index, val);
else insert(x*2+1, mid+1, r, index, val);
tree[x] = max(tree[x*2], tree[x*2+1]);
}
int find(int x, int l, int r, int ll, int rr) {
if (ll > rr) return 0;
if (l == ll && r == rr) {
return tree[x];
}
int mid = (l+r)/2;
if (rr <= mid) return find(x*2, l, mid, ll, rr);
else if (ll >= mid+1) return find(x*2+1, mid+1, r, ll, rr);
else {
int temp1 = find(x*2, l, mid, ll, mid);
int temp2 = find(x*2+1, mid+1, r, mid+1, rr);
return max(temp1, temp2);
}
}
int main() {
while (scanf("%d", &n) != EOF) {
if (n == 0) break;
memset(tree, 0, sizeof(tree));
memset(last, 0, sizeof(last));
flag = true;
maxx = 50001;
for (int i = 1; i <= n; i++) {
scanf("%d%d", &a[i].x, &a[i].y);
}
sort(a+1, a+1+n);
x = 0, y = 0;
init = 1;
for (int i = 1; i <= n; i++) {
if (tot == 0) {
if (find(1, 1, maxx, 1, a[i].y) > last[a[i].y]) flag = false;
} else {
t1 = find(1, 1, maxx, queue[tot].y+1, a[i].y-1);
if (t1 > last[queue[tot].y] || t1 > last[a[i].y]) flag = false;
}
queue[++tot].x = a[i].x;
queue[tot].y = a[i].y;
while (tot > 1 && last[queue[tot].y] <= last[queue[tot-1].y]) {
swap(queue[tot], queue[tot-1]);
tot--;
}
if (i == n || a[i].x != a[i+1].x) {
if (find(1, 1, maxx, queue[tot].y+1, maxx) > last[queue[tot].y]) flag = false;
if (!flag) break;
for (int j = init; j <= i; j++) {
insert(1, 1, maxx, a[j].y, a[j].x);
last[a[j].y] = a[j].x;
}
init = i+1;
x = 0; y = 0;
tot = 0;
}
if (!flag) break;
}
if (flag) printf("YES\n");
else printf("NO\n");
}
}