You have a list of numbers. For many queries, say which number in the list is closest to the query.
What to build
Sort the list once. For each query x, use lower_bound to find the first value that is at least x, then compare it with the value just before it. Print the closer one; if both are equally close, print the smaller.
Requirements
- Sort once, then answer each query in O(log n)
- Handle queries smaller than every value and larger than every value
- On a tie in distance, print the smaller value
Input
The first line has n and q. The second line has n whole numbers. The third line has q queries.
Output
For each query, the closest value, on one line, separated by spaces.
Constraints
1 ≤ n, q ≤ 100,000. All values are between -10⁹ and 10⁹.
Example
Input:
5 4
10 40 20 30 50
27 5 100 35
Output:
30 10 50 30
Why it works
After sorting, the closest value to x is either the first value that is at least x or the one just before it. lower_bound finds that spot in O(log n). The two edge cases are when the spot is the first element (nothing before it) and when it is n (nothing at or after it).
Examples
5 4 10 40 20 30 50 27 5 100 35
30 10 50 30
1 2 8 8 -3
8 8
Hints
Hint 1
pos = lower_bound(a.begin(), a.end(), x) - a.begin();
Hint 2
If pos == n, the answer is a[n - 1]. If pos == 0, the answer is a[0].
Hint 3
Otherwise compare x - a[pos - 1] with a[pos] - x, and prefer a[pos - 1] on a tie. Use long long for the differences.
Solution
Show one correct solution (try it yourself first)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, q;
cin >> n >> q;
vector<long long> a(n);
for (auto& x : a) cin >> x;
sort(a.begin(), a.end());
for (int i = 0; i < q; i++) {
long long x;
cin >> x;
int pos = lower_bound(a.begin(), a.end(), x) - a.begin();
long long ans;
if (pos == n) ans = a[n - 1];
else if (pos == 0) ans = a[0];
else if (x - a[pos - 1] <= a[pos] - x) ans = a[pos - 1];
else ans = a[pos];
cout << ans << " ";
}
cout << "\n";
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step