[BOJ 2512] ์˜ˆ์‚ฐ

 

1. ๋ฌธ์ œ : https://www.acmicpc.net/problem/2512

 

2. ํ’€์ด

์ด๋ถ„ํƒ์ƒ‰ ์กฐ๊ฑด์„ ๋น„๊ตํ•ด๊ฐ€๋ฉฐ +-

 

3. ์ฝ”๋“œ

package baekjoon;

import java.util.*;

class Main {
    private static int[] arr; // ์ง€๋ฐฉ ์˜ˆ์‚ฐ
    private static long answer = 0;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt(); // ์ง€๋ฐฉ์˜ ์ˆ˜
        arr = new int[N];
        for (int i = 0; i < N; i++) {
            arr[i] = sc.nextInt();
        }
        Arrays.sort(arr);
        long M = sc.nextLong(); //์ด ์˜ˆ์‚ฐ
        long left = 0;
        long right = arr[N-1];
        while (left <= right) {
            long mid = (left + right) / 2; //๋‚ด์•ผํ•  ์„ธ๊ธˆ
            long sum = 0; // ๋ชจ๋“  ์ง€๋ฐฉ ์„ธ๊ธˆ ํ•ฉ
            for (int money : arr) {
                if (money >= mid) sum += mid; //๋‚ด๋ผ๋Š” ์„ธ๊ธˆ ๋‚ผ ์ˆ˜ ์žˆ๋Š” ์ง€๋ฐฉ
                else sum += money; //๋ชป๋‚ด๋Š” ์ง€๋ฐฉ์€ ๊ฐ€์ง„ ์ตœ๋Œ€ ๋ˆ๋งŒ ๋ƒ„
            }
            if (sum > M) { // ๋‚ด๋ผ๋Š” ์„ธ๊ธˆ ๋ณด๋‹ค ๋งŽ์€ ๊ฒฝ์šฐ -> ์„ธ๊ธˆ์„  ์ค„์—ฌ๋ณธ๋‹ค.
                right = mid - 1;
            } else { // ๋‚ด๋ผ๋Š” ์„ธ๊ธˆ๋ณด๋‹ค ์ ์€ ๊ฒฝ์šฐ -> ์„ธ๊ธˆ์„ ๋†’์—ฌ์„œ ๋” ์ตœ๊ณ ์˜ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ฐพ๋Š”๋‹ค.
                left = mid + 1;
                answer = Math.max(answer, mid);
            }
        }
        System.out.println(answer);
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ