Binary Search

Um_nik 的名言

"Stop learning useless algorithms, go and solve some problems, learn how to use binary search." ———— Um_nik



一个二分查找的模型

\(Q\) 次询问, 每次询问给出 \(L\) 和 \(R\), 需要回答数组 \(A\) 里面有多少个元素在闭区间 \([L, R]\) 之内。

P3184 [USACO16DEC] Counting Haybales S

#include <bits/stdc++.h>

using i64 = long long;
using u64 = unsigned long long;

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

    int N, Q;
    std::cin >> N >> Q;

    std::vector<int> A(N + 1);
    for (int i = 1; i <= N; i++) {
        std::cin >> A[i];
    }

    std::sort(A.begin() + 1, A.end());

    while (Q--) {
        int l, r;
        std::cin >> l >> r;

        std::cout << std::upper_bound(A.begin() + 1, A.end(), r)
                        - std::lower_bound(A.begin() + 1, A.end(), l) << "\n";
    }
    return 0;
}

P1102 A-B 数对

#include <bits/stdc++.h>

using i64 = long long;
using u64 = unsigned long long;

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

    int N, C;
    std::cin >> N >> C;

    std::vector<int> A(N + 1);
    for (int i = 1; i <= N; i++) {
        std::cin >> A[i];
    }

    std::sort(A.begin() + 1, A.end());

    i64 ans = 0;
    for (int i = 1; i <= N; i++) {
        ans += std::upper_bound(A.begin() + 1, A.end(), A[i] - C)
                - std::lower_bound(A.begin() + 1, A.end(), A[i] - C);
    }
    std::cout << ans;
    return 0;
}

D - Range Count Query

CF1538C Number of Pairs

CF2051D Counting Pairs

D - K-th Nearest

posted @ 2026-07-23 18:55  Smash1  阅读(3)  评论(0)    收藏  举报