21.09.09 기록
백준 알고리즘 14888 풀이
🎆끄적여본 오답…
-항상 막히던 곳에서 역시 막혔다 ~ ..
-operSign이랑 operator 배열은 굳이 없어도 될 것 같긴한데… 모르겠다.🤔
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class B14888 {
public static int[] nums;
public static int[] operCnt = new int[4];
public static final char[] operSign = {'+', '-', 'x', '/'};
public static char[] operator;
public static int max = Integer.MIN_VALUE;
public static int min = 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());
//nums에 N개의 수 저장 -> 수열
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
nums = new int[N];
for(int i = 0; i < N; i++) {
nums[i] = Integer.parseInt(st.nextToken());
}
//operCnt 연산자 개수 저장
st = new StringTokenizer(br.readLine(), " ");
for(int i = 0; i < operCnt.length; i++) {
operCnt[i] = Integer.parseInt(st.nextToken());
}
//operCnt를 기준으로 기호를 char 배열로 저장
operator = new char[N-1];
getOperator();
//수열 x 연산자 조합으로 최댓값, 최솟값 구하기
dfs(0);
System.out.println(max + '\n' + min);
}
public static void getOperator() {
int idx = 0;
for(int i = 0; i < operCnt.length; i++) {
int std = operCnt[i];
for(int j = 0; j < std; j++) {
operator[idx] = operSign[i];
idx++;
}
}
}
public static void dfs(int depth) {
if(depth == operator.length) {
return;
}
//재귀가 어렵다 ㅠㅠ..
}
}
🎆해설(메모리 15.5MB, 시간 148ms로 통과)
-지난 백트래킹 로직과 크게 다른 것이 없어 이해하는데 어렵진 않았다.. 다만 풀지 못했을 뿐😂
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class B14888 {
public static int N;
public static int[] nums;
public static int[] operator = new int[4];
public static int max = Integer.MIN_VALUE;
public static int min = Integer.MAX_VALUE;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
nums = new int[N];
StringTokenizer st = new StringTokenizer(br.readLine(), " ");
for(int i = 0; i < N; i++) {
nums[i] = Integer.parseInt(st.nextToken());
}
st = new StringTokenizer(br.readLine(), " ");
for(int i = 0; i < operator.length; i++) {
operator[i] = Integer.parseInt(st.nextToken());
}
dfs(nums[0], 1);
System.out.println(max + "\n" + min);
}
public static void dfs(int num, int idx) {
if(idx == N) {
max = Math.max(max, num);
min = Math.min(min, num);
return;
}
for(int i = 0; i < operator.length; i++) {
if(operator[i] > 0) {
operator[i]--;
switch (i) {
case 0 : dfs(num + nums[idx], idx+1);
break;
case 1: dfs(num - nums[idx], idx+1);
break;
case 2: dfs(num * nums[idx], idx+1);
break;
case 3: dfs(num / nums[idx], idx+1);
break;
}
operator[i]++;
}
}
}
}