Total time limit: 1000ms memory limit: 65536kB
described
in a non-descending sequence, and find the closest value given element.
Input
The first line contains an integer n, a non-drop sequence length. 1 <= n <= 100000.
The second line contains n integers, the non-descending sequence of elements. All the elements are in the size between 0-1,000,000,000.
The third row contains an integer m, to ask for the number of a given value. 1 <= m <= 10000.
Next m lines, each an integer, the closest element to ask for the given value. All values are given size between 0-1,000,000,000.
Output
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. 8. 5
2
10
. 5
sample output
. 8
. 5
#include<iostream>
#include<cstring>
#include<algorithm>//排序、二分查找算法使用的头文件
using namespace std;
int main(){
int n;
cin>>n;
long long a[n+5];
for(int i=0;i<n;i++){
cin>>a[i];
}
//二分查找需要先排序
sort(a,a+n);
int m;
cin>>m;
long long target[m+5];
for(int i=0;i<m;i++){
cin>>target[i];
long long *temp=lower_bound(a,a+n,target[i]);
if(*temp==target[i]){
//查找的值正好在输入的数据里面,输出
cout<<target[i]<<endl;
}else{
//目标查找值不在数据里面,比较查找值前后的两个值与查找值哪个更接近
if(temp-a>0&&temp-a<n){
//查找的位置不在起始位置,也不再结束位置
if((target[i]-a[temp-a-1])<=(*temp-target[i])){
cout<<a[temp-a-1]<<endl;
}else{
cout<<*temp<<endl;
}
}else if(temp-a==0)
//查找的位置在起始位置
cout<<*temp<<endl;
else if(temp-a==n)
//查找的位置在结束位置
cout<<a[temp-a-1]<<endl;
}
}
return 0;
}