CF600B Queries about less or equal elements 题解 二分

Topic links: http://codeforces.com/problemset/problem/600/B

Title effect:
to give you a length \ (n-\) array \ (A [] \) and a length \ (m \) array \ (B [] \) .
For array \ (B [] \) Each element \ (b_j \) , you need to calculate \ (A [] \) how many elements \ (a_i \) satisfies \ (a_i \ le b_j \) of.

Problem-solving ideas:
This question relates to the algorithm: Two points.
Requires first array \ (A [] \) to sort, then for each \ (b_j \) , greater than or equal binary search \ (b_j \) that the minimum number.
Codes are as follows:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 200020;

int n, m, a[maxn], b[maxn];

int main() {
    cin >> n >> m;
    for (int i = 0; i < n; i ++) cin >> a[i];
    for (int i = 0; i < m; i ++) cin >> b[i];
    sort(a, a+n);
    for (int i = 0; i < m; i ++) {
        if (i) putchar(' ');
        int L = 0, R = n-1, res = -1;
        while (L <= R) {
            int mid = (L + R) / 2;
            if (a[mid] <= b[i]) {
                res = mid;
                L = mid + 1;
            } else {
                R = mid - 1;
            }
        }
        cout << res + 1;
    }
    cout << endl;
    return 0;
}

Of course, we can also use the STL upper_bound function to achieve (upper_bound function returns a particular element of a large number of the smallest address), the code is implemented as follows:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 200020;

int n, m, a[maxn], b[maxn];

int main() {
    cin >> n >> m;
    for (int i = 0; i < n; i ++) cin >> a[i];
    for (int i = 0; i < m; i ++) cin >> b[i];
    sort(a, a+n);
    for (int i = 0; i < m; i ++) {
        if (i) putchar(' ');
        int id = upper_bound(a, a+n, b[i]) - a;
        cout << id;
    }
    cout << endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/quanjun/p/12191307.html