Description
给你一个序列,然后给你m个元素,让你从序列中找出与每个元素最接近的数字输出来,如果有两个就输出两个。
Input
多组输入,第一行给你两个数n(0 < n < 10000000),m(0 < m < n),接下来是数列的n个数,然后再输入m个元素,让你找出最接近每个元素的值。如果有两个,按从小到大输出。
Output
这m个数分别输出最接近每个元素的值,组与组之间输出一个空行。
Sample
Input
8 4
1 2 3 4 5 6 8 11
4
9
2
7
Output
4
8
2
6 8
#include <bits/stdc++.h>
using namespace std;
int a[10000010];
int main()
{
int n,m,x;
while(~scanf("%d %d",&n,&m))
{
for(int i=0; i<n; i++)
{
scanf("%d",&a[i]);
}
sort(a,a+n);
while(m--)
{
scanf("%d",&x);
if(x>a[n-1])
cout<<a[n-1]<<endl;
else if(x<a[0])
cout<<a[0]<<endl;
else
{
int l=0,r=n-1;
int flag=0;
while(l<=r)
{
int mid=(l+r)/2;
if(x==a[mid])
{
cout<<x<<endl;
flag=1;
break;
}
else if(x<a[mid])
r=mid-1;
else if(x>a[mid])
l=mid+1;
}
if(flag==0)
{
if(x-a[r]==a[l]-x)
cout<<a[r]<<" "<<a[l]<<endl;
else if(x-a[r]<a[l]-x)
cout<<a[r]<<endl;
else
cout<<a[l]<<endl;
}
}
}
cout<<endl;
}
return 0;
}