Skip to content

Commit a1ad450

Browse files
committed
add: 백준/랜선 자르기
1 parent 9f320b3 commit a1ad450

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

boj/1654(이진탐색).js

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// 랜선 자르기
2+
// https://www.acmicpc.net/problem/1654
3+
const fs = require('fs');
4+
const stdin = (process.platform === 'linux'
5+
? fs.readFileSync('/dev/stdin').toString().trim()
6+
: `4 11
7+
802
8+
743
9+
457
10+
539
11+
`
12+
).split('\n');
13+
14+
const input = (() => {
15+
let line = 0;
16+
return () => stdin[line++];
17+
})();
18+
19+
function binarySearch(left, right) {
20+
let answer = 0;
21+
while (left <= right) {
22+
const mid = Math.floor((left + right) / 2);
23+
24+
let count = 0;
25+
26+
for (let i = 0; i < K; i++) {
27+
count += Math.floor(arr[i] / mid);
28+
}
29+
30+
if (count >= N) {
31+
left = mid + 1;
32+
answer = Math.max(answer, mid);
33+
continue;
34+
}
35+
right = mid - 1;
36+
}
37+
38+
return answer;
39+
}
40+
41+
const [K, N] = input()
42+
.split(' ')
43+
.map((each) => parseInt(each));
44+
45+
const arr = [];
46+
47+
for (let i = 0; i < K; i++) {
48+
arr.push(parseInt(input()));
49+
}
50+
51+
let max = arr.reduce((prev, cur) => prev + cur);
52+
53+
console.log(binarySearch(1, max));
54+
55+
/*
56+
57+
## How
58+
이진 탐색을 응용한 파나 메트릭 서치를 사용하면 풀 수 있다.
59+
60+
가지고 있는 K 개의 랜선의 길이 중 가장 큰 값을 기준으로 right, 1을 left로 둔다. mid는 left와 right를 더한 값의 절반으로 계산한다.
61+
62+
결국 N 개 이상의 랜선으로 만들 수 있도록 하는 최대 랜선의 길이를 구해야 하는데 이를 위해 K 개의 랜선의 길이를 순회하면서 mid로 나눈 값을 더해나가면 현재 길이로 몇 개의 랜선을 만들 수 있는지 파악할 수 있다.
63+
64+
만약 N 개 미만의 랜선이라면 right에 mid - 1한 값을 더하고 N 개 이상이면 left에 mid + 1한 값을 대입한 뒤 answer에 기존 answer와 mid 중 큰 값을 대입한다.
65+
66+
left와 right가 같아지거나 left가 더 커지면 순회를 종료하고 answer를 출력하면 N 개로 만들었을 때 가장 큰 길이를 구할 수 있다.
67+
68+
69+
## Retrospective
70+
71+
*/

0 commit comments

Comments
 (0)