chillurbrain

3. Двоичный поиск

May 25th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.91 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Main {
  5.  
  6.     static int[] a;
  7.     static int n;
  8.  
  9.     public static boolean 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.         return a[r] == x;
  21.     }
  22.  
  23.     public static void main(String args[]) {
  24.         try (PrintWriter out = new PrintWriter(System.out);) {
  25.             Scanner in = new Scanner(System.in);
  26.             n = in.nextInt();
  27.             int k = in.nextInt();
  28.             a = new int[n];
  29.             for (int i = 0; i < n; i++) a[i] = in.nextInt();
  30.             for (int i = 0; i < k; i++)
  31.                 out.println(binSearch(in.nextInt()) ? "YES" : "NO");
  32.         } catch(Exception e) {
  33.             System.out.println("Exception: " + e);
  34.         }
  35.     }
  36. }
Add Comment
Please, Sign In to add comment