首页 > 代码库 > ACM ——Points in Segments

ACM ——Points in Segments

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 segment A 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           // 5个数 3个区间

1 4 6 8 10        //输入这5个数

0 5            //第一个区间

6 10          //第二个区间

7 100000        //第三个区间

Sample Output

Case 1:

2        //第一个区间有2个数在区间中  1 和4

3        // 第二个区间有3个数在区间中 6 8 10

2                     //第三个区间有 2个数在区间中   7  和  100000

题意:给出一个n位数递增的数列,然后q个区间查询,每个查询问指定的区间覆盖了数列中几个数?

 

用 C++ STL 里的 low_bound 和upper_bound

upper_bound() 返回数列中第一个大于所查询数的位置,或者没有大于所查询的数返回数列长度(越界)

lower_bound()  返回数列中第一个等于或者大于所查询数的位置,或者没有等于,大于所查询数返回数列长度(越界)

 

#include<stdio.h>
#include<algorithm>
using namespace std;
int a[100010];
int main ()
{   
    int n,m,i;
    int N, L=0,k;
    int x, y;
    scanf("%d",&N);
    while (N--)
    {
        
        scanf ("%d %d", &n, &m);
        for (i=0; i<n; i++)
            scanf ("%d", &a[i]);
        printf ("Case %d:\n", ++L);
        while (m --)
        {
            scanf ("%d %d", &x, &y);
            k=upper_bound (a,a+n,y)-a;   //实际上是一个指针
            k-=lower_bound (a,a+n,x)-a;
            printf ("%d\n", k);
        }
    }
    return 0;
}

  

 

ACM ——Points in Segments