[BOJ 2343] ๊ธฐํƒ€ ๋ ˆ์Šจ

 

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

 

2. ํ’€์ด

๊ธฐ์กด ์˜์ƒ ํ•ฉ+ ์ƒˆ๋กœ์šด ์˜์ƒ > ๋น„๋””์˜ค ๊ธธ์ด -> +1

๊ธฐ์กด ์˜์ƒ ํ•ฉ์„ 0์œผ๋กœ ๋งŒ๋“ค๊ณ  ๋‹ค์‹œ ๋ฐ˜๋ณต๋ฌธ

sum += arr[i] ํ•˜๋ฉด 0์œผ๋กœ ๋งŒ๋“  ํ›„์—๋„ ๊ฐ’ ๋”ํ•ด์ฃผ๋Š” ๊ฒƒ ๊ฐ€๋Šฅ (์ธ๋ฑ์Šค ๋ณ€๊ฒฝ ๋ถˆํ•„์š”)

๋ฐ˜๋ณต๋ฌธ ๋‹ค ๋Œ๊ณ  sum์ด 0์ด ์•„๋‹ˆ๋ฉด ๋‚จ์€ ๋น„๋””์˜ค๊ฐ€ ๋‚จ์•„์žˆ๋‹ค๋Š” ์†Œ๋ฆฌ๊ธฐ ๋•Œ๋ฌธ์— +1

 

upper bound, lower bound ์—…๋ฐ์ดํŠธ ํ•ด์ฃผ๋ฉฐ ๋ฐ˜๋ณต

3. ์ฝ”๋“œ

package baekjoon;

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

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());
        int m = Integer.parseInt(st.nextToken());
        int[] arr = new int[n];

        int left = 0;
        int right = 0;
        st = new StringTokenizer(br.readLine());
        for (int i = 0; i < n; i++) {
            arr[i] = Integer.parseInt(st.nextToken());
            right += arr[i];
            left = Math.max(left, arr[i]);
        }

        while (left <= right) {
            int mid = (left + right) / 2;
            int sum = 0;
            int k = 0;
            for (int i = 0; i < n; i++) {
                if (sum + arr[i] > mid) {
                    sum = 0;
                    k++;
                }
                sum += arr[i];
            }

            if (sum != 0) k++;

            if (k > m) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        System.out.println(left);
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ