题目描述
在一个非降序列序列中与给定值 x 最接近的元素
输入描述
第一行包含一个整数 n,为非降序列长度 (1<=n<=100 000)
第 2 行包含 n 个整数,为非降序列的各个元素, 所有元素的大小均在 0~1 000 000 000 范围内。
第 3 行包含一个整数 m, 为要询问的给定值的个数 (1<=m<=10 000)。接下来 m 行,每行一个整数, 为要询问最接近元素的给定值,所有给定值的大小均在 0~1 000 000 000 范围内。
输出描述
输出共 m 行,每行一个整数,为最接近相应给定值的元素值,并保持输入顺序。若有多个元素值满足条件,输出最小的一个。
输入样例
Copy to Clipboard
3 2 5 8 2 10 5
输出样例
Copy to Clipboard
8 5
/*
* @Description: To iterate is human, to recurse divine.
* @Autor: Recursion
* @Date: 2022-04-13 10:59:17
* @LastEditTime: 2022-04-13 11:10:59
*/
#include <bits/stdc++.h>
#define LL long long
using namespace std;
const int maxn = 1e6 + 10;
const int mod = 1e9 + 7;
const int INF = 1e9 + 10;
const int N = 1e6 + 10;
LL a[N];
int n,m;
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> n;
for(int i = 1;i <= n;i ++)
cin >> a[i];
cin >> m;
while(m--){
int q;
cin >> q;
int pos = lower_bound(a + 1, a + 1 + n,q) - a - 1;
if(pos == n){
cout << a[n] << endl;
continue;
}
else if(abs(q - a[pos]) > abs(q - a[pos + 1])){
cout << a[pos + 1] << endl;
}
else
cout << a[pos] << endl;
}
return 0;
}