알고리즘 문제/백준(BOJ)
[백준 14888번] 연산자 끼워넣기 :: 늦깎이 IT
집돌이탈출
2019. 3. 12. 09:56
모든 경우의 수를 모두 탐색하는 문제입니다.
DFS 탐색을 사용하였습니다.
[소스코드]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Queue; import java.util.Stack; import java.util.StringTokenizer; public class Main { public static int N, minVal = Integer.MAX_VALUE, maxVal = Integer.MIN_VALUE; public static int[] temp, arr, expression; public static int[] dirX = new int[] { 0, 0, -1, 1 }; public static int[] dirY = new int[] { 1, -1, 0, 0 }; public static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void main(String[] args) throws Exception { StringTokenizer st = new StringTokenizer(br.readLine()); N = Integer.parseInt(st.nextToken()); arr = new int[N]; temp = new int[N - 1]; expression = new int[4]; st = new StringTokenizer(br.readLine()); for (int i = 0; i < N; i++) arr[i] = Integer.parseInt(st.nextToken()); st = new StringTokenizer(br.readLine()); for (int i = 0; i < 4; i++) expression[i] = Integer.parseInt(st.nextToken()); dfs(1, arr[0]); System.out.println(maxVal); System.out.println(minVal); } public static void dfs(int depth, int totalVal) { if (depth > N - 1) { minVal = Math.min(minVal, totalVal); maxVal = Math.max(maxVal, totalVal); return; } for (int i = 0; i < 4; i++) { if (expression[i] > 0) { expression[i] -= 1; switch (i) { case 0: dfs(depth + 1, totalVal + arr[depth]); break; case 1: dfs(depth + 1, totalVal - arr[depth]); break; case 2: dfs(depth + 1, totalVal * arr[depth]); break; case 3: dfs(depth + 1, totalVal / arr[depth]); break; } expression[i] += 1; } } } } | cs |