Counting Haybales

本文介绍了一种通过排序和二分查找解决区间内元素数量查询问题的高效算法,并提供了完整的C++实现代码。

【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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值