给你n个壁纸,壁纸之间高度相同,按照顺序粘壁纸,问能看见多少张壁纸。
首先壁纸的距离范围太长,无法用数组存储,需要先离散化,然后进行区间更新,用数组维护区间,每个区间数组的值有(-1:这个区间没壁纸;0:这个区间有多个壁纸;1~n:这个区间是第i个壁纸)。代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
#define maxn 30000
#define lmin 1
#define rmax n
#define lson l,(l+r)/2,rt<<1
#define rson (l+r)/2+1,r,rt<<1|1
#define root lmin,rmax,1
#define now l,r,rt
#define int_now int l,int r,int rt
int cl[maxn<<2] , lazy[maxn<<2] , a[maxn] ;
struct node{int id1 , id2 , k ;
}p[maxn];
bool cmp(node a,node b)
{return a.k < b.k ;
}
void push_up(int_now)
{if( !cl[rt<<1] || !cl[rt<<1|1] || cl[rt<<1] != cl[rt<<1|1] )cl[rt] = 0 ;elsecl[rt] = cl[rt<<1|1] ;
}
void push_down(int_now)
{if( lazy[rt] != -1 ){lazy[rt<<1] = lazy[rt<<1|1] = lazy[rt] ;cl[rt<<1] = cl[rt<<1|1] = lazy[rt] ;lazy[rt] = -1 ;}
}
void update(int ll,int rr,int x,int_now)
{if( ll > r || rr < l )return ;if( ll <= l && r <= rr ){cl[rt] = lazy[rt] = x ;return ;}push_down(now);update(ll,rr,x,lson);update(ll,rr,x,rson);push_up(now);
}
void query(int ll,int rr,int_now,int *a)
{if( cl[rt] == -1 )return ;else if(cl[rt] > 0){a[ cl[rt] ] = 1 ;return ;}push_down(now);query(ll,rr,lson,a);query(ll,rr,rson,a);
}
int main()
{int t , i , n , m , l , r , x ;scanf("%d", &t);while(t--){scanf("%d", &m);for(i = 0 ; i < m ; i++){scanf("%d %d", &p[i].k, &p[i+m].k);p[i].id1 = i ;p[i+m].id1 = i+m ;}sort(p,p+2*m,cmp);int temp = -1 ;n = 0 ;for(i = 0 ; i < 2*m ; i++){if( p[i].k == temp )p[i].id2 = n ;else{p[i].id2 = ++n ;temp = p[i].k ;}a[ p[i].id1 ] = p[i].id2 ;}memset(cl,-1,sizeof(cl));memset(lazy,-1,sizeof(lazy));for(i = 0 ; i < m ; i++){update(a[i],a[i+m],i+1,root);}memset(a,0,sizeof(a));query(1,n,root,a);int num = 0;for(i = 1 ; i <= m ; i++)if(a[i])num++ ;printf("%d\n", num);}return 0;
}