【Description】
Farmer John has just arranged his N haybales (1≤N≤100,000) at various points along the one-dimensional road running across his farm. To make sure they are spaced out appropriately, please help him answer Q queries (1≤Q≤100,000), each asking for the number of haybales within a specific interval along the road.
【INPUT FORMAT】
The first line contains N and Q.
The next line contains N distinct integers, each in the range 0…1,000,000,000, indicating that there is a haybale at each of those locations.
Each of the next Q lines contains two integers A and B (0≤A≤B≤1,000,000,000) giving a query for the number of haybales between A and B, inclusive.
【OUTPUT FORMAT】
You should write Q lines of output. For each query, output the number of haybales in its respective interval.
【SAMPLE INPUT】
4 6
3 2 7 5
2 3
2 4
2 5
2 7
4 6
8 10
【SAMPLE OUTPUT】
2
2
3
4
1
0
【题意简述】
给出含有N个数的数列,再给出Q个询问,每个询问给出两个整数l和r,输出在l到r之间有多少个数。
【分析】
先将N个数排序。
设searchl(x)返回在该数列中第一个小于(等于)x的数的下标,searchr(x)返回在该数列中第一个大于(等于)x的数的下标,则答案即为searchr(r)-searchl(l)+1。
#include<cstdio>
#include<algorithm>
using namespace std;
int main()
{
int n,q;
scanf("%d%d",&n,&q);
int a[n+5];
int i;
for(i=1;i<=n;i++) scanf("%d",&a[i]);
sort(a+1,a+n+1);
int x,y;
for(i=1;i<=q;i++){
scanf("%d%d",&x,&y);
printf("%d\n",upper_bound(a+1,a+n+1,y)-lower_bound(a+1,a+n+1,x));
}
return 0;
}
本文介绍了一种通过排序和二分查找解决区间内元素数量查询问题的高效算法,并提供了完整的C++实现代码。

903

被折叠的 条评论
为什么被折叠?



