[Silver II] 랜선 자르기 - 1654
성능 요약
메모리: 27568 KB, 시간: 320 ms
분류
이분 탐색(binary_search), 매개 변수 탐색(parametric_search)
문제 설명
집에서 시간을 보내던 오영식은 박성원의 부름을 받고 급히 달려왔다. 박성원이 캠프 때 쓸 N개의 랜선을 만들어야 하는데 너무 바빠서 영식이에게 도움을 청했다.
이미 오영식은 자체적으로 K개의 랜선을 가지고 있다. 그러나 K개의 랜선은 길이가 제각각이다. 박성원은 랜선을 모두 N개의 같은 길이의 랜선으로 만들고 싶었기 때문에 K개의 랜선을 잘라서 만들어야 한다. 예를 들어 300cm 짜리 랜선에서 140cm 짜리 랜선을 두 개 잘라내면 20cm는 버려야 한다. (이미 자른 랜선은 붙일 수 없다.)
편의를 위해 랜선을 자르거나 만들 때 손실되는 길이는 없다고 가정하며, 기존의 K개의 랜선으로 N개의 랜선을 만들 수 없는 경우는 없다고 가정하자. 그리고 자를 때는 항상 센티미터 단위로 정수길이만큼 자른다고 가정하자. N개보다 많이 만드는 것도 N개를 만드는 것에 포함된다. 이때 만들 수 있는 최대 랜선의 길이를 구하는 프로그램을 작성하시오.
입력
첫째 줄에는 오영식이 이미 가지고 있는 랜선의 개수 K, 그리고 필요한 랜선의 개수 N이 입력된다. K는 1이상 10,000이하의 정수이고, N은 1이상 1,000,000이하의 정수이다. 그리고 항상 K ≦ N 이다. 그 후 K줄에 걸쳐 이미 가지고 있는 각 랜선의 길이가 센티미터 단위의 정수로 입력된다. 랜선의 길이는 231-1보다 작거나 같은 자연수이다.
출력
첫째 줄에 N개를 만들 수 있는 랜선의 최대 길이를 센티미터 단위의 정수로 출력한다.
풀이
이분 탐색, 매개변수 탐색을 활용한 문제다.
이분 탐색을 할 때, start랑 end 범위를 고민하는 게 계속 헷갈리는 것 같다 한 번 정리를 해야 할듯..
N개 이상을 만드는 경우도 포함해야 하기 때문에 매개변수 탐색에 해당한다.
start와 end 범위를 좁혀가면서 N개 이상을 만들었을 경우에 mid값을 ans에 업데이트하면서 반복하였다.
start와 end가 같아졌을 때는 더 탐색할 필요가 없으므로 while문을 빠져 나온다.
입력 가능한 수의 범위가 2의 31승이어서 int형으로도 가능할 거라 생각했는데, start와 end에서 mid를 계산할 때 int의 범위를 넘어갈 수 있다는 걸 놓쳤다.
- 이분 탐색 / 매개변수 탐색 시에 upper bound, lower bound 잘 고민해보기
- 정수의 범위 조심하기
package BOJ.Silver.s2;
import java.util.Scanner;
public class BOJ_1654_랜선자르기 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int K = sc.nextInt();
int N = sc.nextInt();
long[] arr = new long[K];
for (int i = 0; i < K; i++)
arr[i] = sc.nextLong();
long start = 1;
long end = (long) Math.pow(2, 31) + 1;
long ans = 0;
while (start < end) {
long mid = (start + end) / 2;
long tmp = 0;
for (int i = 0; i < K; i++)
tmp += arr[i] / mid;
if (tmp >= N) {
ans = mid;
start = mid + 1;
} else end = mid - 1;
}
System.out.println(ans);
}
}
'문제 풀이 > BOJ' 카테고리의 다른 글
[백준] 3190 - 뱀 (자바 Java) (0) | 2022.12.03 |
---|---|
[백준] 2343 - 기타 레슨 (자바 Java) (0) | 2022.12.03 |
[백준] 11437 LCA , 11438 LCA2 (자바 Java) (0) | 2022.12.01 |
[백준] 2042 - 구간 합 구하기 (자바 Java) : 세그먼트 트리 (0) | 2022.11.29 |
[백준] 19237 - 어른 상어 (자바 Java) (0) | 2022.11.28 |