Приближенный поиск

mail@pastecode.io avatar
unknown
c_cpp
8 months ago
680 B
15
Indexable
Never
#include <bits/stdc++.h>

using namespace std;

int main() {
    int n, m;
    cin >> n >> m;
    int a[n];
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }
    for (int i = 0; i < m; ++i) {
        int x;
        cin >> x;
        int L = 0, R = n - 1;
        // a[k-1] < x <= a[k]
        int k = (lower_bound(a + 0, a + n, x) - a);
    
        if (k == n) {
            cout << a[n - 1] << endl;
        } else if (k == 0) {
            cout << a[0] << endl;
        } else if (x - a[k - 1] <= a[k] - x) {
            cout << a[k - 1] << endl;
        } else {
            cout << a[k] << endl;
        }
    }
    return 0;    
}

Leave a Comment