1 minute read

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

수의 나열이 주어지고 그 사이에 연산자를 끼워 계산한다. 숫자의 순서는 바꿀 수 없다. 연산자 우선순위를 무시하고 앞에서부터 계산한다.

N개의 수와 N-1개의 연산자가 주어지고 최솟값, 최댓값을 출력한다.

입출력1

입력 :
2
5 6
0 0 1 0

출력 :
30
30

입출력2

입력 :
3
3 4 5
1 0 1 0

출력 :
35
17

  • 중복불가
  • 나눗셈은 정수 나눗셈으로 몫만 취한다.

(1) 연산자 뽑기
(2) 계산하기
(3) 최솟값인지 최댓값인지 확인하기

import java.util.*;

public class Main {

         static int N;
         static int[] numArr;
         static ArrayList<String> calcList;
         static String[] selected;
         static boolean[] visited; // 중복 불가
         static int min = Integer.MAX_VALUE;
         static int max = Integer.MIN_VALUE;

        public static void main(String[] args){
            input();
            recursion(1);
            System.out.println(max);
            System.out.println(min);
        }
        public static void input(){
            Scanner sc = new Scanner(System.in);
            N = sc.nextInt(); // 수의 갯수
            numArr = new int[N]; // 수의 나열
            for(int i=0; i<N; i++) {
                numArr[i] = sc.nextInt();
            }
            calcList = new ArrayList<>();
            // 연산자 셋팅
            Map<Integer, String> map = new HashMap<>();
            map.put(0, "+");
            map.put(1, "-");
            map.put(2, "*");
            map.put(3, "/");

            for(int i=0; i<4; i++) {
                int temp = sc.nextInt();
                while(temp > 0) {
                    calcList.add(map.get(i));
                    temp--;
                }
            }

            selected = new String[N]; // 뽑은 것
            visited = new boolean[N];
        }

        public static void recursion(int k) { 
            if(k == N) {
                int result = numArr[0];
                for(int i=1; i<N; i++) {
                    switch (selected[i]) { // (2)
                        case "+" :
                            result += numArr[i];
                            break;
                        case "-" :
                            result -= numArr[i];
                            break;
                        case "*" :
                            result *= numArr[i];
                            break;
                        case "/" :
                            result /= numArr[i];
                            break;
                        }

                    }
                // (3)    
                max = Math.max(max, result);
                min = Math.min(min, result);

            } else {
                for(int cand=0; cand<N-1; cand++) { // (1)
                    if(visited[cand]) {
                        continue;
                    }
                    visited[cand] = true;
                    selected[k] = calcList.get(cand);
                    recursion(k+1);
                    visited[cand] = false;

                }
            }
        }

}