题目链接:http://poj.org/problem?id=2528
线段树比较基础的题目,比较捉急的就是离散化,离散化就是将大的区间映射到小的区间中,具体的看代码吧,这个是傻崽大神的代码,本菜的话决计写不出来这么巧妙的代码,不过不得不说,这次受益匪浅,以后我想我会记住这些东西……
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1
const int maxn = 11111;
bool hash[maxn];
int li[maxn], ri[maxn];
int X[maxn * 3];
int col[maxn << 4];
int cnt;
void PushDown(int rt){
if (col[rt] != -1){
col[rt << 1] = col[rt << 1 | 1] = col[rt];
col[rt] = -1;
}
}
void update(int ll, int rr, int c, int l, int r, int rt){
if (ll <= l && rr >= r){
col[rt] = c;
return;
}
PushDown(rt);
int m = (l + r) >> 1;
if (ll <= m) update(ll, rr, c, lson);
if (rr > m) update(ll, rr, c, rson);
}
void query(int l, int r, int rt){
if (col[rt] != -1){
if (!hash[col[rt]]) cnt += 1;
hash[col[rt]] = true;
return;
}
if (l == r) return;
int m = (l + r) >> 1;
query(lson);
query(rson);
}
int Bin(int key, int n, int X[]){
int l = 0, r = n - 1;
while (l <= r){
int m = (l + r) >> 1;
if (X[m] == key) return m;
if (X[m] < key) l = m + 1;
else r = m - 1;
}
}
int main(){
int t;
scanf("%d", &t);
while (t--){
int n; scanf("%d", &n);
int nn = 0;
for (int i = 0; i < n; i++){
scanf("%d%d", &li[i], &ri[i]);
X[nn++] = li[i];
X[nn++] = ri[i];
}
sort(X, X + nn);
int m = 1;
for (int i = 1; i < nn; i++){
if (X[i] != X[i - 1]) X[m++] = X[i];
}
sort(X, X + m);
for (int i = m - 1; i > 0; i--){
if (X[i] != X[i - 1] + 1) X[m++] = X[i - 1] + 1;
}
sort(X, X + m);
memset(col, -1, sizeof(col));
for (int i = 0; i < n; i++){
int l = Bin(li[i], m, X);
int r = Bin(ri[i], m, X);
update(l, r, i, 0, m, 1);
}
cnt = 0;
memset(hash, 0, sizeof(hash));
query(0, m, 1);
printf("%d\n", cnt);
}
return 0;
}