[线段树+离散化]LightOJ 1089 - Points in Segments (II)

题目描述:

Givennsegments (1 dimensional) andqpoints, for each point you have to find the number of segments which contain that point. A pointpiwill lie in a segmentA BifA ≤ pi≤ B.

For example, if the segments are(6 12), (8 8), (10 12), (8 11), (0 12)and the point is11, then it is contained by4segments.

Input

Input starts with an integerT (≤ 5), denoting the number of test cases.

Each case starts with a line containing two integersn (1 ≤ n ≤ 50000)andq (1 ≤ q ≤ 50000).

Each of the nextnlines contains two integersAkBk(0 ≤ Ak≤ Bk≤ 108)denoting a segment.

Each of the nextqlines contains an integer denoting a point. Each of them range in[0, 108].

Output

For each case, print the case number in a single line. Then for each point, print the number of segments that contain that point.

Sample Input

Output for Sample Input

1

5 4

6 12

8 8

10 12

8 11

0 12

11

12

2

20

Case 1:

4

3

1

0

大意:先给定若干条线段,然后给定Q个询问,询问的形式为给定一个点,输出该点被线段覆盖多少次。

线段树功能:查询,成段更新

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int MAXN = 222222;
int arr[MAXN];
struct Seg{
    int a,b;
}s[MAXN];
int pt[MAXN],cov[MAXN<<2],N,T,S,Q;
void build(int l,int r,int rt){
    cov[rt] = 0;
    if(l==r)return;
    int m = (l+r)>>1;
    build(lson);
    build(rson);
}
void pushDOWN(int rt){
    if(cov[rt]){
        cov[rt<<1]+=cov[rt];
        cov[rt<<1|1]+=cov[rt];
        cov[rt] = 0;
    }
}
void update(int L,int R,int l,int r,int rt){
    if(L<=l&&R>=r){
        cov[rt]++;
        return;
    }
    pushDOWN(rt);
    int m = (l+r)>>1;
    if(m>=L)update(L,R,lson);
    if(m<R)update(L,R,rson);
}
int query(int pos,int l,int r,int rt){
    if(l==r){
        return cov[rt];
    }
    pushDOWN(rt);
    int m = (l+r)>>1;
    if(pos<=m)return query(pos,lson);
    else return query(pos,rson);
}
int bs(int x){
    int l = 0,r = N-1,m;
    while(l<=r){
        m = (l+r)>>1;
        if(arr[m]==x)return m;
        else if(arr[m]>x)r = m-1;
        else l = m+1;
    }
    return -1;
}
int main(){
    scanf("%d",&T);
    for(int cas=1;cas<=T;cas++){
        scanf("%d%d",&S,&Q);N = 0;
        for(int i=0;i<S;i++){
            scanf("%d%d",&s[i].a,&s[i].b);
            arr[N++] = s[i].a;
            arr[N++] = s[i].b;
        }
        for(int i=0;i<Q;i++){
            scanf("%d",&pt[i]);
            arr[N++] = pt[i];
        }
        sort(arr,arr+N);
        int temp = 1;
        for(int i=1;i<N;i++)if(arr[i]!=arr[i-1])arr[temp++] = arr[i];
        N = temp;
        build(0,N-1,1);
        for(int i=0;i<S;i++){
            update(bs(s[i].a),bs(s[i].b),0,N-1,1);
        }
        printf("Case %d:\n",cas);
        for(int i=0;i<Q;i++){
            printf("%d\n",query(bs(pt[i]),0,N-1,1));
        }
    }
    return 0;
}



你可能感兴趣的:(poi)