POJ 2528 Mayor's posters (线段树区间更新、离散化)

题目链接:http://poj.org/problem?id=2528


题意:题目大意:在墙壁上贴广告,广告的版面有大有小,并且贴广告有先后之分,后面贴的广告会覆盖前面的广告,求解最后能看到的广告面,如下图所示:




两种视图,最后从Front View能看见的广告数目是4。

#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
struct node{
	int l, r, m;
	ll val;
};
const int maxn = 10010;
node T[maxn << 4];
int col[maxn];
int ans;
void pushdown(int rt) {
	if(T[rt].val != -1) {  
        T[rt << 1].val = T[rt].val;  
        T[rt << 1 | 1].val = T[rt].val;  
        T[rt].val = -1;  
    }
}
void build(int begin, int end, int rt) {
	T[rt].l = begin;
	T[rt].r = end;
	T[rt].m = (T[rt].l + T[rt].r) >> 1;
	T[rt].val = -1;
	if(begin == end) return ;
	build(T[rt].l, T[rt].m, rt << 1);
	build(T[rt].m + 1, T[rt].r, rt << 1 | 1);
}
void update(int L, int R, int num, int rt) {
	if(L == T[rt].l && T[rt].r == R) {
		T[rt].val = num;
		return ;
	}
	pushdown(rt);
	if(L > T[rt].m) update(L, R, num, rt << 1 | 1);  
    else if(R <= T[rt].m) update(L, R, num, rt << 1);  
    else {  
        update(L, T[rt].m, num, rt << 1);  
        update(T[rt].m + 1, R, num, rt << 1 | 1);  
    }  
    
}
void query(int rt) {
	if(T[rt].val != -1) {
		if(!col[T[rt].val]) ans++;
		col[T[rt].val] = 1;
		return ;
	}
	if(T[rt].l == T[rt].r) return ;
	query(rt << 1);
	query(rt << 1 | 1);
}
int x[maxn<<2], top;
pair q[maxn];
int main() {
	int t;
	scanf("%d", &t);
	int n;
	int tl, tr;
	while(t--) {
		top = 0;
		scanf("%d", &n);
		for(int i = 0; i < n; i++) {
			scanf("%d %d", &q[i].first, &q[i].second);
			x[top++] = q[i].first;
			x[top++] = q[i].second;
		}
		sort(x, x + top);
		int m = 1;
		for(int i = 1; i < top; i++) {
			if(x[i] != x[i - 1]) x[m++] = x[i];
		}
		for(int i = m - 1; i > 0; i--) {
			if(x[i] - 1 != x[i - 1]) x[m++] = x[i] - 1;
		}
		sort(x, x + m);
		build(0, m, 1);
		for(int i = 0; i < n; i++) {
			int l = lower_bound(x, x + m, q[i].first) - x;
			int r = lower_bound(x, x + m, q[i].second) - x;
			update(l, r, i, 1);
		}
		memset(col, 0, sizeof col);
		ans = 0;
		query(1);
		printf("%d\n", ans);
	}
	return 0;
}



你可能感兴趣的:(线段树)