Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- import java.io.*;
- public class Main {
- static int n;
- static int k;
- static int[] a;
- static int binSearch(int x) {
- int l = 0;
- int r = n - 1;
- while (l < r) {
- int m = (l + r) / 2;
- if (a[m] < x)
- l = m + 1;
- else
- r = m;
- }
- if (l > 0 && a[l] != x && Math.abs(a[l-1] - x) <= Math.abs(a[l] - x))
- return a[l-1];
- return a[l];
- }
- public static void main(String args[]) {
- try (PrintWriter out = new PrintWriter(System.out);) {
- Scanner sc = new Scanner(System.in);
- n = sc.nextInt();
- k = sc.nextInt();
- a = new int[n];
- for (int i = 0; i < n; i++)
- a[i] = sc.nextInt();
- for (int j = 0; j < k; j++)
- out.println(binSearch(sc.nextInt()));
- } catch(Exception e) {
- System.out.println("Exception: " + e);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment