【題目描述】
在一個非降序列中,查找與給定值最接近的元素。
【輸入】
第一行包含一個整數n,爲非降序列長度。1 ≤ n ≤ 100000。
第二行包含n個整數,爲非降序列各元素。所有元素的大小均在0-1,000,000,000之間。
第三行包含一個整數m,爲要詢問的給定值個數。1 ≤ m ≤ 10000。
接下來m行,每行一個整數,爲要詢問最接近元素的給定值。所有給定值的大小均在0-1,000,000,000之間。
【輸出】
m行,每行一個整數,爲最接近相應給定值的元素值,保持輸入順序。若有多個值滿足條件,輸出最小的一個。
【輸入樣例】
3 2 5 8 2 10 5
【輸出樣例】
8 5
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <map>
#include <cstdlib>
#define sf(a) scanf("%d\n",&a)
#define pf(a) printf("%.6lf ",a)
#define E 1e-8
#define ms(a) memset(a,0,sizeof a)
#define rep(a,b,c) for(int a=b;a<=c;a++)
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int idata=1e5+5;
ll minn=inf,maxx=-inf;
ll n,ans,t,k;
char *ch;
ll step[idata];
ll temp[idata];
ll cnt;
ll query,judge,flag;
priority_queue< int,vector<int>,greater<int> >q;
pair<int,int>p[idata];
int main()
{
while(cin>>n)
{
rep(i,1,n)
cin>>step[i];
cin>>t;
while(t--)
{
cin>>query;
if(query>step[n])
cout<<step[n]<<endl;
else if(query<step[1])
cout<<step[1]<<endl;
else
{
flag=upper_bound(step+1,step+n,query)-(step);//一開始寫成(step+1)wrong了兩次
if(step[flag]-query>=query-step[flag-1])//注意等於
cout<<step[flag-1]<<endl;
else
cout<<step[flag]<<endl;
}
}
}
return 0;
}