LightOJ - 1088 Points in Segments

Description

Given n points (1 dimensional) and q segments, you have to find the number of points that lie in each of the segments. A point pi will lie in a segmentA B if A ≤ pi ≤ B.

For example if the points are 1, 4, 6, 8, 10. And the segment is 0 to 5. Then there are 2 points that lie in the segment.

Input

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

Each case starts with a line containing two integers n (1 ≤ n ≤ 105) and q (1 ≤ q ≤ 50000). The next line contains n space separated integers denoting the points in ascending order. All the integers are distinct and each of them range in [0, 108].

Each of the next q lines contains two integers Ak Bk (0 ≤ Ak ≤ Bk ≤ 108) denoting a segment.

Output

For each case, print the case number in a single line. Then for each segment, print the number of points that lie in that segment.

Sample Input

1

5 3

1 4 6 8 10

0 5

6 10

7 100000

Sample Output

Case 1:

2

3

2


題解:各找出高位低位區間後,高減低,得數,二分查找


#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;

int num[100010];
int n,q;
void readint(int len){   //讀數據
    int k;
    for(int i = 1; i <= len; i++)
        scanf("%d",&k), num[i] = k;
}

int Bsearch_lower_bound(int Ai){  //找底限位置
    int low = 1,high = n,mid = 0;
    while(low <= high){
        mid = (low+high)>>1;
        if(num[mid] == Ai) return mid;
        if(num[mid] < Ai) low = mid+1;
        else high = mid-1;
    }
    return low;
}

int Bsearch_upper_bound(int Bi){ //找高位位置
    int low = 1,high = n,mid = 0;
    while(low <= high){
        mid = (low+high)>>1;
        if(num[mid] <= Bi) low = mid+1;
        else high = mid-1;
    }
    return low;
}

int main(){
    int T;
    scanf("%d",&T);
    for(int i = 1; i <= T; i++){
        scanf("%d%d",&n,&q);
        printf("Case %d:\n",i);
        readint(n);
        for(int j = 0; j < q; j++){
            int low,high;
            scanf("%d%d",&low,&high);
            low = Bsearch_lower_bound(low);
            high = Bsearch_upper_bound(high);
            printf("%d\n",high-low);
        }
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章