본문 바로가기
Develop/Coding Test | Algorithm

[백준] JAVA 풀이 - 2805: 나무 자르기

by 코젼 2024. 5. 10.
728x90
반응형

https://www.acmicpc.net/problem/2805

 

▶️ 힌트

  • 이분 탐색
  • (결과값 < 기대값) 인 경우, max = mid
  • (결과값 > 기대값) 인 경우, min = mid + 1; //1씩 증가하면서 확인

 

▶️ 풀이

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {

    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int N = Integer.parseInt(st.nextToken());
        long M = Long.parseLong(st.nextToken());

        st = new StringTokenizer(br.readLine());
        long[] arr = new long[N];
        long max = 0;
        long min = 0;

        for (int i=0; i<N; i++) {
            arr[i] = Integer.parseInt(st.nextToken());

            if (max < arr[i]) max = arr[i];
        }

        while (min < max) {

            long result = 0;
            long mid = (min + max) / 2;

            for (long a : arr) {
                if (a - mid > 0) {
                    result += (a - mid);
                }
            }

            if (result < M) {
                max = mid;
            } else {
                min = mid + 1;
            }
        }

        System.out.println(min - 1);
    }
}
728x90
반응형

댓글