Advertisement
chillurbrain

4. Левый и правый двоичный поиск

May 25th, 2016
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.97 KB | None | 0 0
  1. import java.io.*;
  2. import java.util.*;
  3.  
  4. public class Solution {
  5.  
  6.     static int[] a;
  7.     static int n;
  8.     static int m;
  9.  
  10.     public static void binSearch(int x) {
  11.         int l = 0;
  12.         int r = n - 1;
  13.  
  14.         while (l < r) {
  15.             int m = (l + r) / 2;
  16.  
  17.             if (a[m] < x)
  18.                 l = m + 1;
  19.             else
  20.                 r = m;
  21.         }
  22.  
  23.         if (a[r] != x) {
  24.             System.out.println(0);
  25.             return;
  26.         }
  27.  
  28.         int leftResult;
  29.         int rightResult;
  30.  
  31.         int ll = 0;
  32.         int rr = r;
  33.         while (ll < rr) {
  34.             int m = (ll + rr) / 2;
  35.             if (a[m] < x)
  36.                 ll = m + 1;
  37.             else
  38.                 rr = m;
  39.         }
  40.  
  41.         leftResult = ll;
  42.         if (a[ll] != x) {
  43.             if (ll > 0 && a[ll - 1] == x)
  44.                 leftResult--;
  45.             else if (ll < n - 1 && a[ll + 1] == x)
  46.                 leftResult++;
  47.         }
  48.  
  49.         ll = r;
  50.         rr = n - 1;
  51.         while (ll < rr) {
  52.             int m = (ll + rr) / 2;
  53.             if (a[m] > x)
  54.                 rr = m;
  55.             else
  56.                 ll = m + 1;
  57.         }
  58.  
  59.         rightResult = rr;
  60.         if (a[rr] != x) {
  61.             if (rr > 0 && a[rr - 1] == x)
  62.                 rightResult--;
  63.             else if (rr < n - 1 && a[rr + 1] == x)
  64.                 rightResult++;
  65.         }
  66.  
  67.         System.out.println(String.format("%s %s", leftResult + 1, rightResult + 1));
  68.     }
  69.  
  70.     public static void main(String args[]) {
  71.         try (PrintWriter out = new PrintWriter(System.out)) {
  72.             Scanner in = new Scanner(System.in);
  73.             n = in.nextInt();
  74.             m = in.nextInt();
  75.             a = new int[n];
  76.  
  77.             for (int i = 0; i < n; i++) a[i] = in.nextInt();
  78.             for (int i = 0; i < m; i++)
  79.                 binSearch(in.nextInt());
  80.         } catch(Exception e) {
  81.             System.out.println("Exception: " + e);
  82.         }
  83.     }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement