반응형
https://www.acmicpc.net/problem/2805
2805번: 나무 자르기
첫째 줄에 나무의 수 N과 상근이가 집으로 가져가려고 하는 나무의 길이 M이 주어진다. (1 ≤ N ≤ 1,000,000, 1 ≤ M ≤ 2,000,000,000) 둘째 줄에는 나무의 높이가 주어진다. 나무의 높이의 합은 항상 M보
www.acmicpc.net
import java.util.*;
public class Main {
static int[] trees;
static int M;
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int N = sc.nextInt(); //나무의 수
M = sc.nextInt(); //가져가려는 나무 길이
trees = new int[N];
int max=0; //나무 최대 높이
for(int i=0;i<N;i++) {
trees[i]=sc.nextInt();
if(max<trees[i])
max= trees[i];
}
int start =0;
int end = max;
while(start+1<end) {
int mid = (start+end)/2;
if(check(mid)) {
start=mid;
}else {
end = mid;
}
}
System.out.println(start);
}// main()
static boolean check(int cut) { // cut위치에서 나무를 가져갈 수 있는지 없는지 확인
long sum = 0;
long result;
long tree;
for (int i = 0; i < trees.length; i++) {
tree = trees[i];
if (tree >= cut) {
result = tree - cut;
sum += result;
}
}
if (sum >= M) {
return true;
} else {
return false;
}
}//check()
}// class Main
728x90
반응형
'코딩테스트 > 백준' 카테고리의 다른 글
백준 9020 : 골드바흐의 추측 _자바 Java (0) | 2023.01.24 |
---|---|
백준 1541 : 잃어버린 괄호 _자바 Java (0) | 2023.01.23 |
백준 11724 : 연결 요소의 개수 _자바 Java (0) | 2023.01.23 |
백준 4948 : 베르트랑 공준 _자바 Java (0) | 2023.01.21 |
백준 1912 : 연속합 _자바 Java (0) | 2023.01.21 |
댓글