清華OJ範圍查詢

題目:

範圍查詢(Range)

Descriptioin
Let S be a set of n integral points on the x-axis. For each given interval [a, b], you are asked to count the points lying inside.
Input
The first line contains two integers: n (size of S) and m (the number of queries).
The second line enumerates all the n points in S.
Each of the following m lines consists of two integers a and b and defines an query interval [a, b].
Output
The number of points in S lying inside each of the m query intervals.
Example
Input
5 2
1 3 7 9 11
4 6
7 12
Output
0
3
Restrictions
0 <= n, m <= 5 * 10^5
For each query interval [a, b], it is guaranteed that a <= b.
Points in S are distinct from each other.
Coordinates of each point as well as the query interval boundaries a and b are non-negative integers not greater than 10^7.
Time: 2 sec
Memory: 256 MB
描述
數軸上有n個點,對於任一閉區間 [a, b],試計算落在其內的點數。
輸入
第一行包括兩個整數:點的總數n,查詢的次數m。
第二行包含n個數,爲各個點的座標。
以下m行,各包含兩個整數:查詢區間的左、右邊界a和b。
輸出
對每次查詢,輸出落在閉區間[a, b]內點的個數。
樣例
見英文題面
限制
0 ≤ n, m ≤ 5×105
對於每次查詢的區間[a, b],都有a ≤ b
各點的座標互異
各點的座標、查詢區間的邊界a、b,均爲不超過10^7的非負整數
時間:2 sec
內存:256 MB

我的代碼:

#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;
template <class T>
//傳入數組,待查找的值,和區間左右下標
int Binary_Search(T a[], const T&x, int len){
    int left = 0;
    int right = len;
    while(left < right){
        int mid = left + ((right - left)>>1);
        if(x < a[mid]){
            right = mid;
        }else{
            left = mid + 1;
        }
    }
    return --left;
}

template <class T>
void swap(T *a,int x, int y){
    T temp = a[x];
    a[x] = a[y];
    a[y] = temp;
}

template <class T>
int partition2(T *a, int left, int right){
    T key = a[left];
    int l =left + 1;
    int r = right;
    while(l <= r){
    //當內循環會影響外循環的循環變量時,在內循環的循環條件裏一定要加上外循環的循環條件限制!!!
        while(l <= r && a[l] <= key){
            l++;
        }
        while(l <= r && a[r] > key){
            r--;
        }
        if(l<r)  //等於的時候交換是沒有意義的,所以直接l<r即可
            swap(a,l,r);
    }
    swap(a,left,r);
    return r;
}

template <class T>
void quick_sort2(T *a, int left, int right){
    if(left < right){
        int q = partition2(a,left,right);
        quick_sort2(a,left,q-1);
        quick_sort2(a,q+1,right);
    }
}


struct P{
    int x;
    int y;
};
int main()
{
    int n,m;
    scanf("%d %d",&n,&m);
    int a[n];
    P p[m];
    for(int i=0; i<n; ++i){
        scanf("%d",&a[i]);
    }
    quick_sort2(a,0,n-1);
    for(int i=0; i<m; i++){
        scanf("%d %d",&p[i].x,&p[i].y);
        int l = Binary_Search(a,p[i].x-1,n);
        int r = Binary_Search(a,p[i].y,n);
        int ans = r - l;
        printf("%d\n",ans);
    }
    return 0;
}


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