14888번: 연산자 끼워넣기 (acmicpc.net)

 

연산자 4개의 개수가 주어진다. 수가 N개 있으니 N - 1개의 위치에 연산자들을 배치하면 된다.

재귀를 통해 연산자를 선택하고 결과를 누적해 간다.

모든 연산자 선택이 끝나고 결과가 완성되면 최대, 최소를 갱신한다.

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

public class Main {

    static FastReader scan = new FastReader();
    static int N;
    static int[] nums;
    static int[] ops;
    static int MIN = Integer.MAX_VALUE;
    static int MAX = Integer.MIN_VALUE;

    static void dfs(int depth, int sum) {
        if (depth == N - 1) {
            MAX = Math.max(MAX, sum);
            MIN = Math.min(MIN, sum);
            return;
        }

        for (int i = 0; i < 4; i++) {
            if (ops[i] > 0) {
                ops[i]--;
                dfs(depth + 1, calculate(sum, i, nums[depth + 1]));
                ops[i]++;
            }
        }
    }

    static int calculate(int num1, int op, int num2) {
        if (op == 0) {
            return num1 + num2;
        } else if (op == 1) {
            return num1 - num2;
        } else if (op == 2) {
            return num1 * num2;
        } else {
            if (num1 < 0) {
                num1 = -num1;
                return -num1 / num2;
            } else {
                return num1 / num2;
            }
        }
    }

    static void input() {
        N = scan.nextInt();
        nums = new int[N];
        ops = new int[4];

        for (int i = 0; i < N; i++) {
            nums[i] = scan.nextInt();
        }

        for (int i = 0; i < 4; i++) {
            ops[i] = scan.nextInt();
        }
    }

    public static void main(String[] args) {
        input();
        dfs(0, nums[0]);
        System.out.println(MAX);
        System.out.println(MIN);
    }

    static class FastReader {
        BufferedReader br;
        StringTokenizer st;

        public FastReader() {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next() {
            while (st == null || !st.hasMoreElements()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

'Algorithm > BOJ' 카테고리의 다른 글

BOJ 15684 - 사다리 조작  (0) 2024.10.11
BOJ 14889 - 스타트와 링크  (1) 2024.10.11
BOJ 14503 - 로봇 청소기  (2) 2024.10.10
BOJ 14502 - 연구소  (0) 2024.10.10
BOJ 14501 - 퇴사  (1) 2024.10.09

+ Recent posts