这道题目也是简单区间更新的线段树题目,不过题目的数据范围很大,直接搞,时间空间的花费都会异常的高,所以就要用到离散化来优化时间空间复杂度.
何为离散化?........................
简单地说就是对于给出的庞大数据进行一种数据上的缩小. 比如给你一段(1,10000)的区间,由于我们要的不是其区间长度,我们只需要知道这段区间的状态
如何,于是我们可以忽视其长度,把其表示成(1,2)这个区间长度极小的区间,这相当于物理上的质点. 当我们处理的问题上与其区间长度无关时,我们就可以
如何离散化?.........................
举个例子,给出两段区间(1,4)(100,100000).此时应该如何离散,仔细想想可以很容易知道可以把其离散成(1,2),(3,4). 来到这里就简单明了了.把区间的两个端点
存在一个数组中,去重之后就可以对其数组元素进行标号.这样区间长度就实现了离散. 具体实现代码看下我的..................
#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <set>
#include <queue>
#include <vector>
#include <cstdlib>
#include <algorithm>
#define ls u << 1
#define rs u << 1 | 1
#define lson l, mid, u << 1
#define rson mid + 1, r, u << 1 | 1
#define INF 0x3f3f3f3f
using namespace std;
typedef long long ll;
const int M = 2e4 + 100;
const int N = 1e7 + 100;
int tmp[M << 2],vis[M],get_hash[N],a[M];
struct Node{
int l,r;
void readin(){
scanf("%d %d",&l,&r);
}
}p[M];
void pushdown(int u){
if(tmp[u]){
tmp[ls] = tmp[rs] = tmp[u];
tmp[u] = 0;
}
}
void pushup(int u){
if(tmp[ls] == tmp[rs]){
tmp[u] = tmp[ls];
}
}
void update(int L,int R,int c,int l,int r,int u){
int mid = (l + r) >> 1;
if(L <= l && R >= r){
tmp[u] = c;
}
else {
pushdown(u);
if(L <= mid) update(L,R,c,lson);
if(R > mid) update(L,R,c,rson);
pushup(u);
}
}
void query(int l,int r,int u){
if(tmp[u]){
vis[tmp[u]] = 1;
}
else {
int mid = (l + r) >> 1;
query(lson);
query(rson);
}
}
int main(){
//freopen("in","r",stdin);
int T,n,l,r;
cin>>T;
while(T--){
scanf("%d",&n);
int to = 0;
memset(vis,0,sizeof(vis));
memset(tmp,0,sizeof(tmp));
for(int i = 0; i < n; i++){
p[i].readin();
a[to++] = p[i].l;
a[to++] = p[i].r;
}
sort(a,a + to);
to = unique(a,a + to) - a;
for(int i = 0; i < to; i++) get_hash[a[i]] = i + 1; //离散化过程
for(int i = 0; i < n; i++){ //离散化过程
int l,r;
l = get_hash[p[i].l];
r = get_hash[p[i].r];
update(l,r,i + 1,1,to,1);
}
query(1,to,1);
int num = 0;
for(int i = 1; i <= n; i++) if(vis[i]) num++;
printf("%d\n",num);
}
return 0;
}