chillurbrain

1. Приближенный двоичный поиск

May 25th, 2016
488
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.04 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. import java.io.*;
  4. public class Main {
  5.     static int n;
  6.     static int k;
  7.     static int[] a;
  8.  
  9.     static int binSearch(int x) {
  10.         int l = 0;
  11.         int r = n - 1;
  12.         while (l < r) {
  13.             int m = (l + r) / 2;
  14.             if (a[m] < x)
  15.                 l = m + 1;
  16.             else
  17.                 r = m;
  18.         }
  19.  
  20.         if (l > 0 && a[l] != x && Math.abs(a[l-1] - x) <= Math.abs(a[l] - x))
  21.             return a[l-1];
  22.  
  23.         return a[l];
  24.     }
  25.  
  26.     public static void main(String args[]) {
  27.         try (PrintWriter out = new PrintWriter(System.out);) {
  28.             Scanner sc = new Scanner(System.in);            
  29.             n = sc.nextInt();
  30.             k = sc.nextInt();
  31.             a = new int[n];
  32.  
  33.             for (int i = 0; i < n; i++)
  34.                 a[i] = sc.nextInt();
  35.             for (int j = 0; j < k; j++)
  36.                 out.println(binSearch(sc.nextInt()));
  37.         } catch(Exception e) {
  38.             System.out.println("Exception: " + e);
  39.         }
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment