範圍查詢(Range)
清華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
1 #include<cstdio> 2 using namespace std; 3 typedef long long ll; 4 const int N=1e7+10; 5 int a[N]; 6 int main() 7 { 8 int n,m,now; 9 int maxx=0; 10 scanf("%d%d",&n,&m); 11 for(int i=0;i<n;i++) 12 { 13 scanf("%d",&now); 14 a[now]=1; 15 } 16 for(int i=1;i<N;i++) 17 { 18 a[i]=a[i-1]+a[i]; 19 } 20 for(int i=0;i<m;i++) 21 { 22 int x,y; 23 scanf("%d%d",&x,&y); 24 printf("%d\n",a[y]-a[x-1]); 25 } 26 return 0; 27 }