1240: Find the closest element
Time limit: 1000 ms Memory limit: 65536 KB
Number of submissions: 3044 Number of passes: 994
[Title description]
In a non-descending sequence, find the element closest to the given value.
[Input] The
first line contains an integer n, which is a non-descending sequence length. 1 ≤ n ≤ 100000.
The second line contains n integers, each element in non-descending order. The size of all elements is between 0-1,000,000,000.
The third line contains an integer m, which is the number of given values to be asked. 1 ≤ m ≤ 10000.
The next m lines, each line an integer, are to ask for the given value of the closest element. The size of all given values is between 0-1,000,000,000.
[Output]
m lines, each line has an integer, which is the element value closest to the corresponding given value, keeping the input order. If multiple values meet the condition, the smallest one is output.
[Input sample]
3
2 5 8
2
10
5
[Output sample]
8
5
#include<iostream>
using namespace std;
int x,a[100001],minn=2147483647,maxx=2147483647;
void find(int left,int right)
{
int mid=(left+right)/2;
if(x>a[mid])
{
if(x-a[mid]<minn)
{
minn=x-a[mid];
maxx=a[mid];
}
else if(x-a[mid]==minn&&maxx>a[mid])
maxx=a[mid];
if(left!=right)
find(mid+1,right);
}
else if(x==a[mid])
{
maxx=a[mid];
return;
}
else
{
if(a[mid]-x<minn)
{
minn=a[mid]-x;
maxx=a[mid];
}
else if(a[mid]-x==minn&&maxx>a[mid])
maxx=a[mid];
if(left!=right)
find(left,mid);
}
}
int main()
{
int n,m;
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
cin>>m;
for(int i=1;i<=m;i++)
{
cin>>x;
minn=2147483647;
maxx=2147483647;
find(1,n);
cout<<maxx<<endl;
}
return 0;
}