Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.lang.reflect.Array;
- import java.util.*;
- public class Contest1 {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- int[] a = new int[n];
- int k = sc.nextInt();
- for (int i = 0; i < n; i++) {
- a[i] = sc.nextInt();
- }
- int[] b = new int[k];
- for (int i = 0; i < k; i++) {
- b[i] = sc.nextInt();
- }
- System.out.println();
- for (int i = 0; i < k; i++) {
- int up = upperBound(a, b[i], 0, a.length - 1);
- if (up >= 1) {
- if (Math.abs(a[up - 1] - b[i]) <= Math.abs(a[up] - b[i])) {
- System.out.println(a[up - 1]);
- } else System.out.println(a[up]);
- } else System.out.println(a[up]);
- }
- }
- public static int upperBound(int[] a, int x, int left, int right) {
- if (x >= a[right]) return right;
- if (x < a[left]) return left;
- int m = (left + right) / 2;
- while (right - left > 1) {
- m = (left + right) / 2;
- if (a[m] <= x) {
- left = m;
- } else right = m;
- }
- if (a[m - 1] == x && a[m] != x) return m - 1;
- if (a[m + 1] > x && a[m] < x) return m + 1;
- else return m;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement