문제
https://www.acmicpc.net/problem/2805
2805번: 나무 자르기
첫째 줄에 나무의 수 N과 상근이가 집으로 가져가려고 하는 나무의 길이 M이 주어진다. (1 ≤ N ≤ 1,000,000, 1 ≤ M ≤ 2,000,000,000) 둘째 줄에는 나무의 높이가 주어진다. 나무의 높이의 합은 항상 M보
www.acmicpc.net
알고리즘
이분탐색
코드
package com.company;
import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class Test_BinarySearch2 {
static int N, M;
static int MAX = 1000000000;
static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static ArrayList<Integer> treeList = new ArrayList<>();
public static void main(String[] args) throws IOException {
//입력
StringTokenizer st = new StringTokenizer(bf.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
st = new StringTokenizer(bf.readLine());
for (int i = 0; i < N; i++) {
treeList.add(Integer.parseInt(st.nextToken()));
}
go();
}
static public void go() throws IOException {
int left = 1;
int right = MAX;
int ans=0;
while(left<=right){
int mid = (left+right)/2;
if(check(mid)<M){
right=mid-1;
}else{
left=mid+1;
ans= mid;
}
}
bw.write(String.valueOf(ans));
bw.flush();
bw.close();
}
static long check(int h) throws IOException {
long cnt=0;
for(int i=0; i<treeList.size(); i++){
if(treeList.get(i)>h){
cnt+=treeList.get(i)-h;
}
}
return cnt;
}
}
'Algorithm (PS) > 백준' 카테고리의 다른 글
[백준] 1260. DFS와 BFS (Java) (0) | 2023.07.10 |
---|---|
[백준] 10816. 숫자 카드2 (Java) [lower_bound, upper_bound] (0) | 2023.07.08 |
[백준] 1789. 수들의합 (Java) [이분탐색] (0) | 2023.07.08 |
[백준] 2346. 풍선 터트리기 (Java) [Deque] (0) | 2023.07.06 |
[백준] 10799. 쇠 막대기 (Java) [Stack] (0) | 2023.07.06 |