Written for: "Informatics Olympiad through a" Chapter VII Exercise 7
Title Description
In one non-reduced sequence, and find the closest value given element.
Input Format
The first row contains an integer \ (n-\) , non-reduced sequence length. \ (. 1 \ n-Le \ Le 100000 \) .
The second line contains \ (n-\) elements, each sequence of non-reducing element. All the elements are in the size \ (1 \) ~ \ (109 \ ^) between.
The third row contains an integer \ (m \) , number of times to be interrogated. \ (. 1 \ Le m \ 10000 Le \) .
Next \ (m \) lines, each an integer, the closest element to ask for the given value. All size values are given in \ (0 \) ~ \ (109 \ ^) between.
Output Format
\ (m \) lines, each an integer value closest to the corresponding element of a given value, holding the input order. If multiple values satisfy the condition, a minimum output.
Sample input
3
2 5 8
2
10
5
Sample Output
8
5
Topic analysis
This question and "greater than or equal to find the smallest element of x 'to be the same.
We assume that we use "Find the smallest element of x greater than or equal" approach to obtain answers to the corresponding coordinates \ (RES \) , then there will be three cases:
- \ (RES = -1 \) , greater than or equal absence described \ (X \) is the minimum element, that is to say all the numbers less than \ (X \) , then in this case the array \ (A \) last the number of sides \ (a_n \) is the answer;
- \ (RES = 1 \) , description \ (x \) than the array \ (a \) all the elements have to laugh, then the array in this case \ (a \) in front of the number \ (a_1 \ ) is the answer;
- \ (res \ ne -1 and RES \ NE. 1 \) , described \ (a [res] \) is greater than or equal \ (X \) is the smallest element, \ (A [-RES. 1] \) is less than \ ( x \) is the largest element, this time we're going to compare:
- If \ (X - A [-RES. 1] \ Le A [RES] - X \) , returns \ (A [-RES. 1] \) ;
- Otherwise, it returns \ (a [res] \)
So we only need to "find the smallest element of x greater than or equal" code can be done on a slightly modified question head.
Codes are as follows:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100010;
int n, a[maxn], q, x;
// solve函数用于返回大于等于x的最小元素的坐标
int solve(int x) {
int L = 1, R = n, res = -1;
while (L <= R) {
int mid = (L + R) / 2;
if (a[mid] >= x) {
res = mid;
R = mid - 1;
}
else L = mid + 1;
}
return res;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i ++) cin >> a[i];
cin >> q;
while (q --) {
cin >> x;
int res = solve(x);
if (res == -1) {
cout << a[n] << endl;
}
else if (res == 1) {
cout << a[1] << endl;
}
else {
if (x - a[res-1] <= a[res] - x)
cout << a[res-1] << endl;
else
cout << a[res] << endl;
}
}
return 0;
}