Skip to content

Commit e965ea7

Browse files
authored
Create b2805.md
1 parent b8ad13f commit e965ea7

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

juseong/binary_search/b2805.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
주어지는 나무의 수는 1 ≤ N ≤ 1,000,000이며 나무의 길이는 1 ≤ M ≤ 2,000,000,000 이다.
2+
3+
나무의 길이를 구하는 문제인데 완전 탐색을 하게 되면 20억 * 100만이 되게 되어서 시간초과가 나게 된다.
4+
5+
시간을 어떻게 줄일 수 있을까? 여기서는 이분탐색을 통해 해결할 수 있다. logN의 시간 복잡도를 가지게 되는데 계속해서 반씩 줄여나가기때문이다.
6+
7+
그리고 주의할점이 있는데 값이 크니 long으로 선언해야한다.
8+
9+
10+
```
11+
package binary_search;
12+
13+
import java.util.Arrays;
14+
import java.util.Scanner;
15+
16+
public class b2805 {
17+
/*
18+
나무 M 미터가 필요
19+
절단기에 최대값을 구하라
20+
*/
21+
22+
public static void main(String[] args) {
23+
24+
Scanner sc = new Scanner(System.in);
25+
String[] str = sc.nextLine().split(" ");
26+
int N = Integer.parseInt(str[0]); // 나무의 수
27+
int M = Integer.parseInt(str[1]); // 가져가려는 나무의 길이
28+
Integer[] trees = Arrays.stream(sc.nextLine().split(" "))
29+
.map(Integer::parseInt)
30+
.toArray(Integer[]::new);
31+
32+
long start = 0;
33+
long end = Arrays.stream(trees)
34+
.max(Integer::compare).get();
35+
long result = 0;
36+
37+
while (start <= end) {
38+
long mid = (start + end) / 2;
39+
40+
int sum = 0;
41+
for (Integer tree : trees) {
42+
long num = tree - mid;
43+
if(num > 0) {
44+
sum += num;
45+
}
46+
}
47+
48+
if(sum >= M) {
49+
result = mid;
50+
start = mid + 1;
51+
} else {
52+
end = mid - 1;
53+
}
54+
}
55+
System.out.println(result);
56+
57+
}
58+
}
59+
```

0 commit comments

Comments
 (0)