[Link] https://AtCoder.jp/contests/typical90/tasks/typical90_g
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
StringBuilder sb = new StringBuilder();
int[] a, b, tmp;
int n, q, min;
n = Integer.parseInt(br.readLine());
a = new int[n];
st = new StringTokenizer(br.readLine());
for(int i = 0; i < n; i++) a[i] = Integer.parseInt(st.nextToken());
Arrays.sort(a);
q = Integer.parseInt(br.readLine());
b = new int[q];
for(int i = 0; i < q; i++) b[i] = Integer.parseInt(br.readLine());
for(int i = 0; i < q; i++) {
int v = b[i];
int l = 0, r = a.length - 1, mid;
min = Integer.MAX_VALUE;
while(l < r - 1) {
mid = (l + r) / 2;
if(a[mid] > v) {
r = mid;
}
else if(a[mid] == v) {
l = r = mid;
break;
}
else {
l = mid;
}
}
sb.append(Math.min(Math.abs(a[r] - v), (Math.abs(a[l] - v)))).append("\n");
}
System.out.print(sb);
}
}