Skip to content

Commit 05e8ad1

Browse files
committed
add: 백준/휴게소 세우기
1 parent 526b748 commit 05e8ad1

1 file changed

Lines changed: 71 additions & 0 deletions

File tree

boj/1477(이진탐색).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/1477
3+
4+
const fs = require('fs');
5+
const stdin = (process.platform === 'linux'
6+
? fs.readFileSync('/dev/stdin').toString().trim()
7+
: `6 7 800
8+
622 411 201 555 755 82
9+
`
10+
).split('\n');
11+
12+
const input = (() => {
13+
let line = 0;
14+
return () => stdin[line++];
15+
})();
16+
17+
function binarySearch(left, right) {
18+
while (left <= right) {
19+
const mid = Math.floor((left + right) / 2);
20+
21+
let newGasStation = 0;
22+
23+
for (let i = 1; i < N + 2; i++) {
24+
const distance = arr[i] - arr[i - 1];
25+
newGasStation += Math.floor(distance / mid);
26+
if (distance % mid === 0) {
27+
newGasStation--;
28+
}
29+
}
30+
31+
if (newGasStation <= M) {
32+
right = mid - 1;
33+
continue;
34+
}
35+
36+
left = mid + 1;
37+
}
38+
39+
return left;
40+
}
41+
42+
const [N, M, L] = input()
43+
.split(' ')
44+
.map((each) => parseInt(each));
45+
46+
const arr = input()
47+
.split(' ')
48+
.map((each) => parseInt(each));
49+
50+
arr.unshift(0);
51+
arr.push(L);
52+
arr.sort((a, b) => a - b);
53+
54+
console.log(binarySearch(1, L - 1));
55+
56+
/*
57+
58+
## How
59+
이 문제도 이분 탐색을 활용한 파라메트릭 서치를 사용하여 풀이했다.
60+
61+
0부터 L까지 이미 존재하는 휴게소 사이로 M 개만큼의 휴게소가 각각 1개 이상씩 들어가야 한다는 것이 핵심 포인트이다. 이 경우에 첫 번째 휴게소까지의 거리가 최소가 되는 값을 구하면 된다.
62+
63+
0과 L을 입력으로 주어지는 휴게소 위치 앞뒤로 넣고 left를 1, right를 L - 1로 둔다. left가 right보다 커지기 전까지 순회하며 mid를 두 값의 합의 절반으로 구한다.
64+
65+
새로운 주유소의 위치를 카운트할 변수를 만들고 N + 2 만큼 순회하면서 (두 주유소 거리 / mid) 한 만큼 해당 변수를 증가시키고 나머지가 0인 경우 겹친 경우라는 의미이므로 1 감소시킨다.
66+
67+
해당 카운트 변수의 값이 M보다 크면 left에 mid + 1을 넣고 아니라면 right에 mid - 1을 넣어 left를 출력하면 최소가 되는 첫 번째 휴게소까지의 거리를 구할 수 있다.
68+
69+
## Retrospective
70+
71+
*/

0 commit comments

Comments
 (0)