7788: 快速查找 二分查找/迭代器指针

描述

 

有n个数字,a1,a2,...,an

给出左右两个端点l和r,你的任务找到有多少个数字在l和r之间(包括端点)。

 

 

输入

 

输入的第一行有一个n(1≤n≤105)。

第二行包含n个数字,a1,a2,...,an(1≤a≤109);

第三行有一个k(1≤k≤105)。

接下来k行,每行有两个数字l和r(1≤l≤r≤109)。

 

 

输出

 

只有一行输出,有k个整数,每个数之间有一个空格。

 

 

样例输入

 

5
10 1 10 3 4
4
1 10
2 9
3 4
2 2

样例输出

 5 2 2 0 

一开始想着用map+双指针,还是太慢了,看了看题解才知道要用二分的统计

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0);

    int n;
    cin >> n;
    vector<ll> a(n);
    for(int i = 0; i < n; i++) cin >> a[i];

    // Sort the array for binary search
    sort(a.begin(), a.end());

    int k;
    cin >> k;
    ll l, r;
    cin >> l >> r;

    // Use binary search to find the positions of l and r
    vector<ll>::iterator l_it = lower_bound(a.begin(), a.end(), l);
    vector<ll>::iterator r_it = upper_bound(a.begin(), a.end(), r);

    // Calculate the number of elements between l and r
    int count = distance(l_it, r_it);
    cout << count;
    k--;
    while(k--) {
        ll l, r;
        cin >> l >> r;

        // Use binary search to find the positions of l and r
        l_it = lower_bound(a.begin(), a.end(), l);
        r_it = upper_bound(a.begin(), a.end(), r);

        // Calculate the number of elements between l and r
        int count = distance(l_it, r_it);
        cout << " " << count;
    }

    return 0;
}

 

posted @ 2023-10-16 00:33  CRt0729  阅读(13)  评论(0编辑  收藏  举报