Skip to content

Commit 526b748

Browse files
committed
add: 백준/예산
1 parent a1ad450 commit 526b748

1 file changed

Lines changed: 72 additions & 0 deletions

File tree

boj/2512(이진탐색).js

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
// 예산
2+
// https://www.acmicpc.net/problem/2512
3+
const fs = require('fs');
4+
const stdin = (process.platform === 'linux'
5+
? fs.readFileSync('/dev/stdin').toString().trim()
6+
: `4
7+
120 110 140 150
8+
485
9+
`
10+
).split('\n');
11+
12+
const input = (() => {
13+
let line = 0;
14+
return () => stdin[line++];
15+
})();
16+
17+
function binarySearch(left, right) {
18+
let answer = 0;
19+
while (left <= right) {
20+
const mid = Math.floor((left + right) / 2);
21+
22+
let sum = 0;
23+
24+
for (let i = 0; i < N; i++) {
25+
if (arr[i] >= mid) {
26+
sum += mid;
27+
continue;
28+
}
29+
30+
sum += arr[i];
31+
}
32+
33+
if (sum <= M) {
34+
left = mid + 1;
35+
answer = Math.max(answer, mid);
36+
continue;
37+
}
38+
39+
right = mid - 1;
40+
}
41+
42+
return answer;
43+
}
44+
45+
const N = parseInt(input());
46+
47+
const arr = input()
48+
.split(' ')
49+
.map((each) => parseInt(each));
50+
51+
const M = parseInt(input());
52+
53+
let max = Math.max(...arr);
54+
55+
console.log(binarySearch(1, max));
56+
57+
/*
58+
59+
## How
60+
이 문제도 이진 탐색 - 파나 메트릭 서치를 사용하면 풀 수 있다.
61+
62+
left는 1, right는 요청한 예산 중 가장 큰 값으로 정한다. 이 둘을 더해 2로 나눈 값을 mid로 하여 left가 right보다 클 때까지 반복한다.
63+
64+
N 번 만큼 순회하면서 값을 더해가는데 mid보다 index에 해당하는 요청 예산이 크거나 같으면 mid 값을 더하고 아니면 해당 요청 예산을 더해나간다.
65+
66+
다 더한 값이 총예산보다 작을 경우 right에 mid - 1을 대입하고 아니라면 left에 mid + 1을 대입한다. 만약 이전에 answer에 값이 대입되어 있는 경우 mid가 더 크면 mid를 answer에 대입한다.
67+
68+
순회가 끝난 후 answer를 출력하면 요구한 값인 배정된 예산 중 최댓값을 구할 수 있다.
69+
70+
## Retrospective
71+
72+
*/

0 commit comments

Comments
 (0)