https://www.acmicpc.net/problem/14888
접근 :
- 입력 받은 수를 이용하여 DFS 방식으로 모든 경우의 수를 확인
- 입력 받은 연산자 수를 고려하여, 가능한 경우에만 연산을 실행하고 최댓값과 최소값을 출력
코드구현 :
import java.io.*;
public class Main {
private static int n;
private static int max;
private static int min;
private static int[] nums;
private static int[] ops;
private static StringBuilder sb;
static void input() throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
nums = new int[n+1];
ops = new int[5];
String[] inputs = br.readLine().split(" ");
for(int i = 1 ; i <= n ; i++) nums[i] = Integer.parseInt(inputs[i-1]);
inputs = br.readLine().split(" ");
for(int j = 1 ; j <= 4 ; j++) ops[j] = Integer.parseInt(inputs[j-1]);
max = Integer.MIN_VALUE;
min = Integer.MAX_VALUE;
sb = new StringBuilder();
br.close();
}
static void recFunc(int now, int temp_res){
if(now == n){
max = max < temp_res ? temp_res : max;
min = min > temp_res ? temp_res : min;
return;
}
for(int i = 1 ; i <= 4 ; i++){
if (ops[i] == 0) continue;
ops[i]--;
recFunc(now + 1, calFunc(temp_res, nums[now+1], i));
ops[i]++;
}
}
static int calFunc(int a, int b, int ops){
if(ops == 1) return a + b;
if(ops == 2) return a - b;
if(ops == 3) return a * b;
if(ops == 4) return a / b;
return 0;
}
public static void main(String[] args) throws IOException{
input();
recFunc(1, nums[1]);
System.out.println(sb.append(max).append('\n').append(min).toString());
}
}
'JAVA > Coding Test' 카테고리의 다른 글
[JAVA] 백준 1759 암호 만들기_브루트포스 (0) | 2024.05.20 |
---|---|
[JAVA] 백준 1182 부분수열의 합_브루트포스 (0) | 2024.05.18 |
[JAVA] 백준 4673 셀프 넘버_브루트포스 (0) | 2024.02.04 |
[JAVA] 백준 7785 회사에 있는 사람_집합과 맵 (0) | 2023.04.17 |
[JAVA] 백준 14215 세 막대_기하: 직사각형과 삼각형 (0) | 2023.04.13 |