문제풀기 : [백준14888 톱니바퀴]
import java.io.*;
public class Main14888_연산끼워넣기 {
static int N;
static int[] numbers, opers;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine().trim());
numbers = new int[N];
String[] input = br.readLine().trim().split(" ");
for(int i=0; i<N; i++) {
numbers[i] = Integer.parseInt(input[i]);
}
input = br.readLine().trim().split(" ");
opers = new int[N-1];
int n,index=0;
for(int i=0; i<4; i++) {
n = Integer.parseInt(input[i]);
for(int j=0; j<n; j++) {
opers[index++] = i;
}
}
perm(0);
System.out.println(max);
System.out.println(min);
}
// 0:+, 1:- ,2:* ,3:/
static int cal() {
int cal = numbers[0];
for(int i=0; i<N-1; i++) {
switch(opers[i]) {
case 0:
cal += numbers[i+1];
break;
case 1:
cal -= numbers[i+1];
break;
case 2:
cal *= numbers[i+1];
break;
case 3:
cal /= numbers[i+1];
break;
}
}
return cal;
}
static int tmp, max=Integer.MIN_VALUE, min = Integer.MAX_VALUE;
static void perm(int depth) {
if(depth == N-1) {
tmp = cal();
if(tmp > max) max = tmp;
if(tmp < min) min = tmp;
return;
}
for(int i=depth; i<N-1; i++) {
swap(i, depth);
perm(depth+1);
swap(i, depth);
}
}
static void swap(int p1, int p2) {
int tmp = opers[p1];
opers[p1] = opers[p2];
opers[p2] = tmp;
}
}
PREVIOUS[삼성기출]백준15683 - 감시