Answer the question
In order to leave comments, you need to log in
How to implement approximate binary search?
Implement an approximate binary search algorithm.
Specifications Input
The first line of the input contains numbers N and K (0NK100001 ). The second line contains N numbers of the first array, sorted in non-decreasing order, and the third line contains K numbers of the second array. Each number in both arrays modulo does not exceed 2*10^9.
Output
For each of the K numbers print in a separate line the number from the first array that is closest to the given one. If there are several of them, print the smallest of them.
Where is the mistake?
const q=100000;
type s = array[1..q] of integer;
var mas,mas2: s;
var n,k,i,l,r,c: integer;
begin
readln(n,k);
for i:=1 to n do read(mas[i]);
for i:=1 to k do read(mas2[i]);
for i:=1 to k do
begin
l:=1;
r:=n+1;
while l<r-1 do
begin
c:=(l+r) div 2;
if mas2[i]<mas[c] then
r:=c
else
l:=c;
end;
if l<>r then
begin
if abs(mas[r]-mas2[i])<abs(mas[l]-mas2[i]) then
writeln(mas[r])
else writeln(mas[l]);
end
else writeln(mas[l])
end;
end.
Answer the question
In order to leave comments, you need to log in
At a minimum, your binary search could end up with r = n+1, which would cause the code in if l <> r to fail.
The algorithm is like this.
1. Implement a binary search specifying where to insert (see Wikipedia).
2. If you insert before the first position or behind the last - return resp. first or last number.
3. Otherwise, find out which is closer from the (i − 1)-th and the i-th.
At home I will check where there is an error in binary search, they like to make mistakes in it.
In addition, your code is purely Olympiad, I would separate the working logic from generating the output file.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question