본문 바로가기
Algorithm/백준

[백준] 연산자 끼워넣기 14888번 - java

by jackWillow 2021. 11. 2.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Main {

	private static int N;
	private static int[] A;
	private static int maxNum = Integer.MIN_VALUE;
	private static int minNum = Integer.MAX_VALUE;
	
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(br.readLine());
		A = new int[N];
		int[] pmmd = 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++) {
			pmmd[i] = Integer.parseInt(st.nextToken());
		}
		
		cal(0, 0, 0, pmmd);
		
		System.out.println(maxNum);
		System.out.println(minNum);
		br.close();
	}
	
	private static void cal(int ret, int op, int depth, int[] pmmd) {
		if(op == 0) ret += A[depth];
		if(op == 1) ret -= A[depth];
		if(op == 2) ret *= A[depth];
		if(op == 3) ret /= A[depth];
		
		if(depth == N - 1) {
			maxNum = ret > maxNum ? ret : maxNum;
			minNum = ret < minNum ? ret : minNum;
			return;
		}
		
		for(int i = 0; i < 4; i++) {
			if(pmmd[i] != 0) {
				pmmd[i]--;
				cal(ret, i, depth + 1, pmmd);
				pmmd[i]++;
			}
		}
	}
	
}
반응형