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