清华学堂 Range

时间:2023-01-22 23:55:24

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

这道题目,好早以前就接触过,那时候数据结构刚学,什么也不懂,今年又来刷这套题了,感觉还好

题目求 [a, b] 内所有的元素个数,二分搜索,求下界,对a求它严格的下界, 对b求它不严格的下界,搞定。

这道题目不用二分,只能拿一部分分数。

 #include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int MAX_SIZE = 5E5 + ;
int num[MAX_SIZE];
int a[MAX_SIZE]; void quick_sort(int s[], int l, int r)
{
if(l < r)
{
int i = l, j = r, x = s[l];
while(i < j)
{
while(i < j && s[j] >= x)
j--;
if(i < j)
s[i++] = s[j]; while(i < j && s[i] < x)
i++;
if(i < j)
s[j--] = s[i];
}
s[i] = x;
quick_sort(s, l, i-);
quick_sort(s, i+, r);
}
} ///二分查下届
int BSearchLowerBound(int arry[], int low, int high, int target)
{
if(high < low || target <= arry[low])
return -;
int mid = (low + high + ) / ;
while(low < high)
{
if(arry[mid] < target)
low = mid;
else
high = mid - ;
mid = (low + high + )/;
}
return mid;
} int BSearchLowerBound_1(int arry[], int low, int high, int target)
{
if(high < low || target < arry[low])
return -;
int mid = (low + high + ) / ;
while(low < high)
{
if(arry[mid] <= target)
low = mid;
else
high = mid - ;
mid = (low + high + )/;
}
return mid;
} int main()
{
int n, m;
int x, y, ans;
while(~scanf("%d %d", &n, &m))
{
for(int i = ; i < n; i++)
{
scanf("%d", num+i);
}
//quick_sort 下标从 0 开始
quick_sort(num, , n-); for(int i = ; i < m; i ++)
{
scanf("%d %d", &x, &y); ans = BSearchLowerBound_1(num, , n-, y) - BSearchLowerBound(num, , n-, x); printf("%d\n", ans);
}
}
return ;
}