SPOJ 138. Election Posters 离散化

本文介绍了一种利用离散化技术优化线段树数据结构的方法,通过将区间端点映射到数轴并进行排序去重,再用数组记录每个区间对应的海报编号,最终统计不同海报的数量。

            题意配上插图很直白,但是由于数据量大,要优化,这个题是的线段树的模板题,看了好长时间也没看懂,学习别人的代码,用离散化做的。

           把所有区间端点离散到一条数轴上,用数组x[ ]存,(x[a]=b表示数轴上第a+1个点值是b)然后排序,去重(unique函数),剩下len个点。对于每一个区间,找到区间两个端点在数轴上的位置a1和a2,用数组f[ ]标记,f[i]=j表示数轴上第i+1个点是海报j. 这样数轴上保存的就是最上面的海报的名称。最后对数轴上0到len的点扫描一遍,统计海报的种类即可。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#define MAXN 40003
using namespace std;
typedef struct node
{
    int l,r;
} node;
int main()
{
    //freopen("in.txt","r",stdin);
    int x[MAXN*2],vis[MAXN],f[MAXN];
    node post[MAXN];
    int cas,n,hg,ans;
    scanf("%d",&cas);
    while(cas--)
    {
        scanf("%d",&n);
        memset(vis,0,sizeof(vis));
        hg=0;
        for(int i=0; i<n; i++)
        {
            scanf("%d%d",&x[hg],&x[hg+1]);
            post[i].l=x[hg];
            post[i].r=x[hg+1];
            hg+=2;
        }
        sort(x,x+hg);
        int len=unique(x,x+hg)-x;
        for(int i=0; i<n; i++)
        {
            int L=lower_bound(x,x+len,post[i].l)-x;
            int R=lower_bound(x,x+len,post[i].r)-x;
            for(int j=L; j<=R; j++)
                f[j]=i;
        }
        ans=0;
        for(int i=0; i<len; i++)
        {
            if(!vis[f[i]])
                ans++;
            vis[f[i]]=1;
        }
        cout<<ans<<endl;
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值