代码:
// Problem: 01:查找最接近的元素
// Contest: OpenJudge - NOI - 1.11编程基础之二分查找
// URL: http://noi.openjudge.cn/ch0111/01/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
//
// Powered by CP Editor (https://cpeditor.org)
#include <bits/stdc++.h>
using namespace std;
int n, m;
int a[114514];
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
sort(a, a + n);
cin >> m;
while (m--)
{
int q;
cin >> q;
if (q < a[0])
cout << a[0] << endl;
if (q > a[n - 1])
cout << a[n - 1] << endl;
else
{
int *lbd = lower_bound(a, a + n, q);
int *upd = upper_bound(a, a + n, q);
if (abs(*upd - q) < abs(*lbd - q))
{
cout << *upd << endl;
}
else
{
cout << *lbd << endl;
}
}
}
}