传送门:POJ2528
题意:在墙上贴海报,海报可以互相覆盖,问最后可以看见几张海报 思路:这题数据范围很大,直接搞超时+超内存,需要离散化: 离散化简单的来说就是只取我们需要的值来用,比如说区间[1000,2000],[1990,2012] 我们用不到[-∞,999][1001,1989][1991,1999][2001,2011][2013,+∞]这些值,所以我只需要1000,1990,2000,2012就够了,将其分别映射到0,1,2,3,在于复杂度就大大的降下来了 所以离散化要保存所有需要用到的值,排序后,分别映射到1~n,这样复杂度就会小很多很多 而这题的难点在于每个数字其实表示的是一个单位长度(并非一个点),这样普通的离散化会造成许多错误 给出下面两个简单的例子应该能体现普通离散化的缺陷: 1-10 1-4 5-10 1-10 1-4 6-10 为了解决这种缺陷,我们可以在排序后的数组上加些处理,比如说[1,2,6,10] 如果相邻数字间距大于1的话,在其中加上任意一个数字,比如加成[1,2,3,6,7,10],然后再做线段树就好了.
线段树中每个点表示的是最后显示哪个海报。
关于DISCUSS里的数据疑问,感觉这个帖子讲的挺好的,推荐一下:http://poj.org/showmessage?message_id=164890
代码:
#include<stdio.h> #include<iostream> #include<string.h> #include<math.h> #include<algorithm> #include<queue> #include<stack> #include<set> #include<vector> #include<map> #define ll long long #define pi acos(-1) #define inf 0x3f3f3f3f #define lson l,mid,rt<<1 #define rson mid+1,r,rt<<1|1 using namespace std; typedef pair<int,int>P; const int MAXN=10010; int L[MAXN],R[MAXN],hash[MAXN<<2],book[MAXN<<2]; int col[MAXN<<4]; void pushdown(int rt) { if(col[rt]!=-1) { col[rt<<1]=col[rt<<1|1]=col[rt]; col[rt]=-1; return ; } } void update(int L,int R,int id,int l,int r,int rt) { if(L<=l&&r<=R) { col[rt]=id; return ; } pushdown(rt); int mid=(l+r)>>1; if(L<=mid)update(L,R,id,lson); if(R>mid)update(L,R,id,rson); } void query(int l,int r,int rt) { if(l==r) { if(col[rt]!=-1) book[col[rt]]=1; return ; } pushdown(rt); int mid=(l+r)>>1; query(lson); query(rson); } int main() { int t; scanf("%d",&t); while(t--) { int n,cnt=0,ans=0; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d%d",L+i,R+i); hash[cnt++]=L[i]; hash[cnt++]=R[i]; } sort(hash,hash+cnt); cnt=unique(hash,hash+cnt)-hash; for(int i=cnt-1;i>0;i--) if(hash[i]>hash[i-1]+1) hash[cnt++]=hash[i-1]+1; sort(hash,hash+cnt); memset(col,-1,sizeof(col)); for(int i=0;i<n;i++) { int l=lower_bound(hash,hash+cnt,L[i])-hash;//找到原数据离散化后对应的数 int r=lower_bound(hash,hash+cnt,R[i])-hash; update(l,r,i,0,cnt-1,1); } memset(book,0,sizeof(book)); query(0,cnt-1,1); for(int i=0;i<cnt;i++)ans+=book[i]; printf("%d\n",ans); } return 0; }
