POJ 2528 Mayor's posters (线段树+离散化+区间覆盖)

题意:n(n<=10000) 个人依次贴海报,给出每张海报所贴的范围li,ri(1<=li<=ri<=10000000) 。求出最后还能看见多少张海报。

思路:由于数据范围比较大,用数组存不下,所以可以离散化成n的范围,而这题的离散化也比较特殊,因为查询的时候是一个一个点向右查找的,如果遇到1 10,1 4,6 10这种数据,那么会被离散化成1 4,1 2,3 4,这样计算的时候就只有两种颜色了,实际上有三种颜色,所以可以在离散化后每两个距离大于1的点之间再加一个点,比如小的+1。初始化直接memset(sum,-1,sizeof(sum))而不用再build,因为涂色是从0开始。update时找到左右区间直接赋值即可。因为要求海报的种数,所以用一个vis数组来存某个颜色是否计算过,没有被计算过而且有颜色答案就++(注意这里不用查到l==r,因为只要有区间有这种颜色就行了)。l==r的时候要return,不然递归会卡死。

#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=10005;
int vis[maxn<<3],sum[maxn<<4];
int li[maxn<<1],ri[maxn<<1],lsh[maxn<<2];
void pushDown(int rt)
{
    if(sum[rt]!=-1)
    {
        sum[rt<<1]=sum[rt<<1|1]=sum[rt];
        sum[rt]=-1;
    }
}
void update(int L,int R,int C,int l,int r,int rt)
{
    if(L<=l&&r<=R)
    {
        sum[rt]=C;
        return ;
    }
    pushDown(rt);
    int m=(l+r)>>1;
    if(m>=L)
    {
        update(L,R,C,l,m,rt<<1);
    }
    if(m<R)
    {
        update(L,R,C,m+1,r,rt<<1|1);
    }
}
int ans;
void query(int l,int r,int rt)
{
    if(!vis[sum[rt]]&&sum[rt]!=-1)
    {
        ans++;
        vis[sum[rt]]=1;
        return ;
    }
    if(l==r)
        return;
    pushDown(rt);
    int m=(l+r)>>1;
    query(l,m,rt<<1);
    query(m+1,r,rt<<1|1);
}
int main()
{
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        memset(sum,-1,sizeof(sum));
        memset(vis,0,sizeof(vis));
        int tot=0;
        for(int i=0; i<n; i++)
        {
            scanf("%d%d",&li[i],&ri[i]);
            lsh[tot++]=li[i];
            lsh[tot++]=ri[i];
        }
        sort(lsh,lsh+tot);
        int mm=unique(lsh,lsh+tot)-lsh;
        int tt=mm;
        for(int i=1; i<tt; i++)
        {
            if(lsh[i]-lsh[i-1]>1)
            {
                lsh[mm++]=lsh[i-1]+1;
            }
        }
        sort(lsh,lsh+mm);
        for(int i=0; i<n; i++)
        {
            int x=lower_bound(lsh,lsh+mm,li[i])-lsh+1;
            int y=lower_bound(lsh,lsh+mm,ri[i])-lsh+1;
            update(x,y,i,1,mm,1);
        }
        ans=0;
        query(1,mm,1);
        printf("%d\n",ans);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值