https://www.acmicpc.net/problem/1654
1. 아이디어
랜선에 대한 매개 변수 이분 탐색을 활용하면 해결할 수 있다.
2. 문제풀이
이분 탐색은 랜선의 길이를 찾고 count 메서드는 찾은 랜선의 길이로 잘랐을 때 랜선의 개수를 구하도록 구성했다.
랜선의 개수가 동일한 길이가 여러 개일 때 최대 길이를 찾아야 하므로 매개변수 이분 탐색의 Upper Bound로 N개를 만들 수 있는 최대 길이를 초과하는 최초 길이를 구하고 1을 빼서 값을 구하는 방식으로 구현했고 랜선의 길이가 int형 최대 범위와 일치해서 이분 탐색을 할 때 최초 high 값을 이보다 크게 설정해줘야 했다.
3. 코드
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int K = Integer.parseInt(st.nextToken());
int N = Integer.parseInt(st.nextToken());
int[] arr = new int[K];
for (int i = 0; i < K; i++) {
arr[i] = Integer.parseInt(br.readLine());
}
int maxLen = binarySearchUpperBound(arr, N);
System.out.println(maxLen);
}
private static int binarySearchUpperBound(int[] arr, int target) {
long low = 0;
long high = Integer.MAX_VALUE + 1L;
while (low < high) {
long mid = (low + high) / 2;
int cnt = count(arr, mid);
if (cnt >= target) low = mid + 1;
else high = mid;
}
return (int) (high - 1);
}
private static int count(int[] arr, long len) {
int cnt = 0;
for (int n : arr) {
cnt += (int) (n / len);
}
return cnt;
}
}
4. 후기
'코딩테스트 준비 > 백준' 카테고리의 다른 글
[백준] 16401번 - 과자 나눠주기 [Java] (0) | 2025.01.13 |
---|---|
[백준] 2805번 - 나무 자르기 [Java] (0) | 2025.01.13 |
[백준] 10816번 - 숫자 카드 2 [Java] (0) | 2025.01.13 |
[백준] 10815번 - 숫자 카드 [Java] (0) | 2025.01.13 |
[백준] 2473번 - 세 용액 [Java] (0) | 2025.01.13 |