D - Mayor's posters POJ - 2528(区间覆盖/线段树/漂浮法)

对一个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);
	}
}

思路就是倒序让线段向上漂浮,飘到顶层就把这条线段打上标记,最后数一下有几个标记就可以了

恩。。很神奇,去接着学线段树了!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值