题意:在墙上贴海报,海报可以互相覆盖,问最后可以看见几张海报
思路:这题数据范围很大,直接搞超时+超内存,需要离散化:
离散化简单的来说就是只取我们需要的值来 用,比如说区间[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,4][1,2][3,4]
线段2覆盖了[1,2],线段3覆盖了[3,4],那么线段1是否被完全覆盖掉了呢?
例子一是完全被覆盖掉了,而例子二没有被覆盖

为了解决这种缺陷,我们可以在排序后的数组上加些处理,比如说[1,2,6,10]
如果相邻数字间距大于1的话,在其中加上任意一个数字,比如加成[1,2,3,6,7,10],然后再做线段树就好了.
线段树功能:update:成段替换 query:简单hash

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <queue>
#include <cmath>
#include <algorithm>
using namespace std;
#define M 11111
#define ls node<<1,l,m
#define rs node<<1|1,m+1,r
int n,cnt;
bool hash[M];
int li[M],ri[M],X[M*3];
int tree[M<<4];
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;
    }
    return -1;
}
void pushdown(int node)
{
    if(tree[node]!=-1)
    {
        tree[node<<1]=tree[node<<1|1]=tree[node];
        tree[node]=-1;
    }
}
void update(int node,int l,int r,int L,int R,int c)
{
    if(L<=l&&r<=R)
    {
        tree[node]=c;
        return ;
    }
    pushdown(node);
    int m=(l+r)>>1;
    if(L<=m) update(ls,L,R,c);
    if(m<R) update(rs,L,R,c);
}
void query(int node,int l,int r)
{
    if(tree[node]!=-1)
    {
        if(!hash[tree[node]]) cnt++;
        hash[tree[node]]=true;
        return ;
    }
    if(l==r) return;
    int m=(l+r)>>1;
    query(ls);
    query(rs);
}
int main()
{
    //freopen("in.txt","r",stdin);
    int t;
    scanf("%d",&t);
    while(t--)
    {
        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];
        }
        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(tree,-1,sizeof(tree));
        for(int i=0;i<n;i++)
        {
            int l=Bin(li[i],m,X);
            int r=Bin(ri[i],m,X);
            update(1,0,m,l,r,i);
        }
        cnt=0;
        memset(hash,false,sizeof(hash));
        query(1,0,m);
        printf("%d\n",cnt);
    }
    return 0;
}