Question 1 Range query (Range)

There are n points on the number axis. For any closed interval [a, b], try to calculate the number of points falling within it.
Requirements:
0 ≤ n, m ≤ 5×10^5
For each query interval [a, b],
the coordinates of each point with a ≤ b are different

Input format:
the first line includes two integers: the total number of points n, and the number of queries m.
The second line contains n numbers, which are the coordinates of each point.
The following m lines each contain two integers: the left and right boundaries a and b of the query interval.

Output format:
For each query, output the number of points falling in the closed interval [a, b].

Input example:
5 2
1 3 7 9 11
4 6
7 12

Sample output:
0
3

code:

//本题的逻辑结构:线性表
//本题的存储结构:顺序
//解题思路和算法:二分查找,答案为大于右边界的个数-大于等于左边界的个数
//效率:时间复杂度O(n+mlogn)、空间复杂度O(n):
//测试数据: 
/*
(1)
输入:
5 2
1 3 7 9 11
4 6
7 12
输出:
0
3
*/
#include <bits/stdc++.h>
#define rep(i,a,b) for(auto i=(a);i<=(b);++i)
#define dep(i,a,b) for(auto i=(a);i>=(b);--i)

using namespace std;
typedef long long ll;
const ll N = 5e5+10;

int s[N];

void AC(){
    
    
    int n,m;
    scanf("%d %d",&n,&m);
    rep(i,1,n){
    
    
        scanf("%d",&s[i]);
    }
    sort(s+1,s+1+n);
    while(m--){
    
    
        int a,b;/* 区间左右边界 */
        scanf("%d %d",&a,&b);
        
        /* 大于右边界的个数-大于等于左边界的个数 */
        int ans = upper_bound(s+1,s+1+n,b)-lower_bound(s+1,s+1+n,a);
        printf("%d\n",ans);
    }
}
/*

*/
int main(){
    
    
    int _ = 1;/* 样例组数 */
    //scanf("%d",&_);
    while(_--){
    
    
        AC();
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_51152918/article/details/126687712