本文共 3839 字,大约阅读时间需要 12 分钟。
The citizens of Bytetown, AB, could not stand that the candidates in the mayoral election campaign have been placing their electoral posters at all places at their whim. The city council has finally decided to build an electoral wall for placing the posters and introduce the following rules:
Input
The first line of input contains a number c giving the number of cases that follow. The first line of data for a single case contains number 1 <= n <= 10000. The subsequent n lines describe the posters in the order in which they were placed. The i-th line among the n lines contains two integer numbers l i and ri which are the number of the wall segment occupied by the left end and the right end of the i-th poster, respectively. We know that for each 1 <= i <= n, 1 <= l i <= ri <= 10000000. After the i-th poster is placed, it entirely covers all wall segments numbered l i, l i+1 ,... , ri.
Output
For each input data set print the number of visible posters after all the posters are placed.
The picture below illustrates the case of the sample input.Sample Input
151 42 68 103 47 10
Sample Output
4
因为区间最大为10000000,如果不预处理直接存的话一方面会爆内存,另一方面肯定也会超时,所以我们需要预处理下,用离散化将区间范围缩小。但是直接离散化跑线段树的话会不对。因为一个点表示的是一个块。
这里引用别人博客的反例:
如三张海报为:1~10 1~4 6~10
离散化时 X[ 1 ] = 1, X[ 2 ] = 4, X[ 3 ] = 6, X[ 4 ] = 10
第一张海报时:墙的1~4被染为1; 第二张海报时:墙的1~2被染为2,3~4仍为1; 第三张海报时:墙的3~4被染为3,1~2仍为2。 最终,第一张海报就显示被完全覆盖了,于是输出2,但实际上明显不是这样,正确输出为3。新的离散方法为:在相差大于1的数间加一个数,例如在上面1 4 6 10中间加5(算法中实际上1,4之间,6,10之间都新增了数的)
X[ 1 ] = 1, X[ 2 ] = 4, X[ 3 ] = 5, X[ 4 ] = 6, X[ 5 ] = 10
这样之后,第一次是1~5被染成1;第二次1~2被染成2;第三次4~5被染成3
最终,1~2为2,3为1,4~5为3,于是输出正确结果3。
引用博客:https://blog.csdn.net/zezzezzez/article/details/80230026然后就是写线段树区间更新了。
#include#include #include #include using namespace std;const int maxn=1e5+5;int n,t;struct qu{ int l,r;};qu a[maxn];int b[maxn<<2];int tree[maxn<<4];int vis[maxn<<4];int ans,cnt;void push_down (int rt){ if(tree[rt]!=-1) { tree[rt<<1]=tree[rt<<1|1]=tree[rt]; tree[rt]=-1; }}void update (int l,int r,int x,int nl,int nr,int rt){ if(nl>=l&&nr<=r) { tree[rt]=x; return; } int m=(nl+nr)>>1; push_down(rt); if(m>=l) update (l,r,x,nl,m,rt<<1); if(r>m) update (l,r,x,m+1,nr,rt<<1|1);}void query(int l,int r,int rt){ if(tree[rt]!=-1) { if(vis[tree[rt]]==0) { ans++; vis[tree[rt]]=1; } return; } if(l==r) return ; int m=(l+r)>>1; push_down(rt); query(l,m,rt<<1); query(m+1,r,rt<<1|1);}int main(){ scanf("%d",&t); while(t--) { scanf("%d",&n); cnt=ans=0; memset (tree,-1,sizeof(tree)); memset (vis,0,sizeof(vis)); for (int i=0;i 1) b[cnt1++]=b[i-1]+1; } sort(b,b+cnt1); for (int i=0;i