• 문제 링크
17124번: 두 개의 배열
정수 배열 A 와 B가 있다. A는 총 n개의 서로 다른 양의 정수를 포함하고 B는 총 m개의 서로 다른 양의 정수를 포함한다. A, B를 이용해서 길이가 n인 새로운 배열 C를 만들어보자. C[i] 는 배열 B에 있
www.acmicpc.net
• 풀이 코드
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
public class Main {
static int[] a, b;
public static void main(String[] args) throws IOException {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int t = read();
StringBuilder sb = new StringBuilder();
while (t-- > 0) {
int n = read(), m = read();
a = new int[n];
for (int i = 0; i < n; i++) a[i] = read();
b = new int[m];
for (int i = 0; i < m; i++) b[i] = read();
Arrays.sort(b);
long sum = 0;
for (int i = 0; i < n; i++) sum += binarySearch(a[i]);
sb.append(sum).append("\n");
}
bw.write(sb.toString());
bw.flush();
}
private static int binarySearch(int key) {
int low = 0, high = b.length - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
if (b[mid] < key) low = mid + 1;
else high = mid - 1;
}
if (low == b.length) return b[b.length - 1];
if (high < 0) return b[0];
return Math.abs(key - b[low]) < Math.abs(key - b[high]) ? b[low] : b[high];
}
private static int read() throws IOException {
int c, n = System.in.read() & 15;
while ((c = System.in.read()) > 32) n = (n << 3) + (n << 1) + (c & 15);
return n;
}
}
'Problem Solving > Baekjoon' 카테고리의 다른 글
[백준] 13777 Hunt The Rabbit - BinarySearch / Java (0) | 2023.08.13 |
---|---|
[백준] 19592 장난감 경주 - BinarySearch / Java (0) | 2023.08.12 |
[백준] 13702 이상한 술집 - BinarySearch / Java (0) | 2023.08.10 |
[백준] 18265 MooBuzz - BinarySearch / Java (0) | 2023.08.09 |
[백준] 1072 게임 - BinarySearch / Java (0) | 2023.08.08 |
댓글