轉自:http://www.notonlysuccess.com/index.php/segment-tree-complete/
題意:在牆上貼海報,海報可以互相覆蓋,問最后可以看見幾張海報
思路:這題數據范圍很大,直接搞超時+超內存,需要離散化:
離散化簡單的來說就是只取我們需要的值來用,比如說區間[1000,2000],[1990,2012] 我們用不到[-∞,999][1001,1989][1991,1999][2001,2011][2013,+∞]這些值,所以我只需要1000,1990,2000,2012就夠了,將其分別映射到0,1,2,3,在於復雜度就大大的降下來了
所以離散化要保存所有需要用到的值,排序后,分別映射到1~n,這樣復雜度就會小很多很多
而這題的難點在於每個數字其實表示的是一個單位長度(並且一個點),這樣普通的離散化會造成許多錯誤(包括我以前的代碼,poj這題數據奇弱)
給出下面兩個簡單的例子應該能體現普通離散化的缺陷:
1-10 1-4 5-10
1-10 1-4 6-10
為了解決這種缺陷,我們可以在排序后的數組上加些處理,比如說[1,2,6,10]
如果相鄰數字間距大於1的話,在其中加上任意一個數字,比如加成[1,2,3,6,7,10],然后再做線段樹就好了.
線段樹功能:update:成段替換 query:簡單hash

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL rt<<1
#define RR rt<<1|1
#define lson l,m,LL
#define rson m+1,r,RR
#define bug puts("bugbug");
const int maxn = 11111;
bool hash[10010];
int col[maxn<<4];
struct node{
int l,r;
}q[10010];
int ans;
int x[maxn<<2];
void pushdown(int rt){
if(col[rt]!=-1){
col[LL]=col[RR]=col[rt];
col[rt]=-1;
}
}
void update(int L,int R,int c,int l,int r,int rt){
if(L<=l&&r<=R){
col[rt]=c;
return ;
}
pushdown(rt);
int m=(l+r)>>1;
if(L<=m) update(L,R,c,lson);
if(R>m) update(L,R,c,rson);
}
void query(int l,int r,int rt){
if(col[rt]!=-1){
if(!hash[col[rt]]) ans++;
hash[col[rt]]=true;
return;
}
if(l==r) return;
int m=(l+r)>>1;
query(lson);
query(rson);
}
int main(){
int n,i,j,t;
scanf("%d",&t);
while(t--){
int cnt=0;
scanf("%d",&n);
for(i=0;i<n;i++){
scanf("%d%d",&q[i].l,&q[i].r);
x[cnt++]=q[i].l;x[cnt++]=q[i].r;
}
sort(x,x+cnt);
int m=1;
for(i=1;i<cnt;i++) if(x[i]!=x[i-1]) x[m++]=x[i];
for(i=m-1;i>=1;i--) if(x[i]!=x[i-1]+1) x[m++]=x[i-1]+1;
sort(x,x+m);
memset(col,-1,sizeof(col));
for(i=0;i<n;i++){
int l=lower_bound(x,x+m,q[i].l)-x;
int r=lower_bound(x,x+m,q[i].r)-x;
update(l,r,i,0,m,1);
}
memset(hash,false,sizeof(hash));
ans=0;
query(0,m,1);
printf("%d\n",ans);
}
return 0;
}