对一个10000000长度的区域用线段去覆盖,问你最后能看到几条线段
分类在线段树,也是线段树被卡的第一题,等学会了线段树做法在更吧,
在poj上看到有人提到漂浮法,试了一发,感觉好神奇,贴代码:
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<algorithm>
#include<queue>
#include<string>
using namespace std;
int t, n, a, b;
#define maxn 10001
int l[maxn];
int r[maxn];
int ans[maxn];
void cover(int a, int b, int to, int id) {
while (to <= n && (b < l[to] || a > r[to])) {
to++;
}
if (to == n+1) {
ans[id] = b - a + 1; return;
}
if (a < l[to]) {
cover(a, l[to] - 1, to + 1, id);
}
if (b > r[to]) {
cover(r[to] + 1, b, to + 1, id);
}
}
int main() {
scanf("%d", &t);
while (t--) {
memset(ans, 0, sizeof(ans));
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d %d", &l[i], &r[i]);
}
for (int i = n; i >= 1; i--) {
cover(l[i], r[i], i + 1, i);
}
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (ans[i])cnt++;
}
printf("%d\n", cnt);
}
}
思路就是倒序让线段向上漂浮,飘到顶层就把这条线段打上标记,最后数一下有几个标记就可以了
恩。。很神奇,去接着学线段树了!