이분 탐색 문제를 풀어 보았다.
https://www.acmicpc.net/problem/29755
29755번: 블랙홀과 소행성
첫 번째 줄에 블랙홀의 수 $N$과 소행성의 수 $M$이 공백으로 구분되어 주어진다. $(1 \le N, M \le 200\,000)$ 두 번째 줄에 $N$개의 정수 $b_1$, $b_2$, $\cdots$, $b_N$이 공백으로 구분되어 주어진다. $(-1\,000\,000
www.acmicpc.net
문제의 공식의 최소값을 구하는 문제이다.
공식을 잘 살펴보 |b-a| 해당 부분이 작을수록 최소값을 가질수 있는 것으로 보인다.
해당 값이 결국 작으려면 블랙홀과 행성의 거리 차가 가장 짧은 것을 찾으면된다. 각 행성별로 거리 차이 * 무게가 가장 높은게 최소 P 값이라고 생각할 수 있겠다
일반 탐색을 사용하는경우 시간초과가 발생이 높아 블랙홀을 정렬후 이분탐색을 진행하면 된다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
public static void main(String[] args) throws IOException {
solution();
}
public static void solution() throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
int[] hole = new int[N];
int[] a = new int[M];
int[] w = new int[M];
st = new StringTokenizer(br.readLine());
for (int i=0; i < N; i++) {
hole[i] = Integer.parseInt(st.nextToken());
}
for (int i=0 ; i < M ; i++) {
st = new StringTokenizer(br.readLine());
a[i] = Integer.parseInt(st.nextToken());
w[i] = Integer.parseInt(st.nextToken());
}
Arrays.sort(hole);
int answer = 0;
for (int i=0; i < M ; i++) {
answer = Math.max(Math.abs(binarySearch(hole, 0, N - 1, a[i]) - a[i]) * w[i], answer);
}
System.out.println(answer);
}
public static int binarySearch(int[] hole, int left, int right, int target) {
while (left <= right) {
int mid = (left + right) / 2;
if (hole[mid] == target) {
return target;
} else if (hole[mid] < target) {
left = mid + 1;
} else {
right = mid -1;
}
}
if (left >= hole.length) {
return hole[right];
} else if (right < 0) {
return hole[left];
} else {
int gap1 = Math.abs(target - hole[left]);
int gap2 = Math.abs(target - hole[right]);
return gap1 < gap2 ? hole[left] : hole[right];
}
}
}
결과
'Coding Test' 카테고리의 다른 글
백준 점프왕 쩰리 (Large)(16174) (0) | 2024.03.18 |
---|---|
백준 보드점프(3372) (2) | 2024.03.17 |
백준 국기 색칠하기(30702) (0) | 2024.03.13 |
백준 삼각 그래프(4883) (0) | 2024.03.12 |
백준 스타트링크(5014) (0) | 2024.03.11 |