[BOJ 16637] ๊ด„ํ˜ธ์ถ”๊ฐ€ํ•˜๊ธฐ

 

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

 

2. ํ’€์ด

๋กœ์ง์€ ์ƒ๊ฐ๋‚ฌ๋Š”๋ฐ ๊ตฌํ˜„์ด ์–ด๋ ค์› ๋˜ ๋ฌธ์ œ

์—ฐ์‚ฐ์ž๋ฅผ ๋‹ด๋Š” ๋ฐฐ์—ด์„ ๋”ฐ๋กœ ๋นผ์คฌ์œผ๋ฉด ์ƒ๊ฐ๋‚ฌ์„์ˆ˜๋„

dfs๋กœ ์™„์ „ํƒ์ƒ‰ํ•˜์—ฌ max๊ฐ’ ์—…๋ฐ์ดํŠธ

 

3. ์ฝ”๋“œ

package baekjoon;

import java.util.*;

public class Main {
    static int ans;
    static ArrayList<Character> ops;
    static ArrayList<Integer> nums;

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        String input = sc.next();

        ops = new ArrayList<>();
        nums = new ArrayList<>();

        for (int i = 0; i < N; i++) {
            char c = input.charAt(i);
            if (c == '+' || c == '-' || c == '*') {
                ops.add(c);
                continue;
            }
            nums.add(Character.getNumericValue(c));
        }

        ans = Integer.MIN_VALUE;
        DFS(nums.get(0), 0);

        System.out.println(ans);
    }

    // ์—ฐ์‚ฐ
    public static int calc(char op, int n1, int n2) {
        switch (op) {
            case '+':
                return n1 + n2;
            case '-':
                return n1 - n2;
            case '*':
                return n1 * n2;
        }
        return -1;
    }

    // DFS
    public static void DFS(int result, int opIdx) {
        // ์ฃผ์–ด์ง„ ์—ฐ์‚ฐ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์ดˆ๊ณผํ•˜์˜€์„ ๊ฒฝ์šฐ.
        if (opIdx >= ops.size()) {
            ans = Math.max(ans, result);
            return;
        }

        // ๊ด„ํ˜ธ๊ฐ€ ์—†๋Š” ๊ฒฝ์šฐ
        int res1 = calc(ops.get(opIdx), result, nums.get(opIdx + 1));
        DFS(res1, opIdx + 1);

        // ๊ด„ํ˜ธ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ
        if (opIdx + 1 < ops.size()) {
            // result์˜ ์˜ค๋ฅธ์ชฝ์— ์žˆ๋Š” ๊ฐ’์„ ์—ฐ์‚ฐํ•จ.
            int res2 = calc(ops.get(opIdx + 1), nums.get(opIdx + 1), nums.get(opIdx + 2));
            res2 = calc(ops.get(opIdx), result, res2);

            // ํ˜„์žฌ result์™€ ๋ฐฉ๊ธˆ ๊ตฌํ•œ ๊ด„ํ˜ธ ๊ฐ’์„ ์—ฐ์‚ฐํ•œ ๊ฒฐ๊ณผ์™€ ๊ด„ํ˜ธ ์˜ค๋ฅธ์ชฝ์— ์กด์žฌํ•˜๋Š” ์—ฐ์‚ฐ์ž์˜ ์ธ๋ฑ์Šค๋ฅผ ๋„˜๊น€.
            DFS(res2, opIdx + 2);
        }
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ