728x90
https://www.acmicpc.net/problem/14888
14888번: 연산자 끼워넣기
첫째 줄에 수의 개수 N(2 ≤ N ≤ 11)가 주어진다. 둘째 줄에는 A1, A2, ..., AN이 주어진다. (1 ≤ Ai ≤ 100) 셋째 줄에는 합이 N-1인 4개의 정수가 주어지는데, 차례대로 덧셈(+)의 개수, 뺄셈(-)의 개수, 곱
www.acmicpc.net
import java.io.*;
import java.util.*;
public class Main {
static int[] A;
static int[] calCheck;
static int maxValue = Integer.MIN_VALUE;
static int minValue = Integer.MAX_VALUE;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(br.readLine());
A = new int[N];
calCheck = new int[4];
StringTokenizer st = new StringTokenizer(br.readLine());
for (int i = 0; i < N; i++) {
A[i] = Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(br.readLine());
for (int i = 0; i<4; i++) {
calCheck[i] = Integer.parseInt(st.nextToken());
}
DFS(1,A[0]);
System.out.println(maxValue);
System.out.println(minValue);
}
private static void DFS(int idx, int sum) {
if (idx == A.length) {
maxValue = Math.max(maxValue, sum);
minValue = Math.min(minValue, sum);
return;
}
for(int i = 0; i<4; i++) {
if (calCheck[i] < 1) {
continue;
}
calCheck[i]--;
switch (i) {
case 0:
DFS(idx+1, sum+A[idx]); break;
case 1:
DFS(idx+1, sum-A[idx]); break;
case 2:
DFS(idx+1, sum*A[idx]); break;
case 3:
DFS(idx+1, sum/A[idx]); break;
}
calCheck[i]++;
}
}
}
회고
- 모든 경우의 수를 탐색하는 문제였다.
- 생각보다 구현하는게 까다로웠다.
'Algorithm Study > BaekJoon (JAVA)' 카테고리의 다른 글
백준 1764_듣보잡_JAVA (0) | 2024.03.27 |
---|---|
백준 1181_단어 정렬_JAVA (0) | 2024.03.26 |
백준 1929_소수 구하기_JAVA (1) | 2024.03.22 |
백준 1541_잃어버린 괄호_JAVA (0) | 2024.03.21 |
백준 1920_수 찾기_JAVA (0) | 2024.03.21 |