๋ณธ๋ฌธ์œผ๋กœ ๋ฐ”๋กœ๊ฐ€๊ธฐ

https://www.acmicpc.net/problem/14888

 

14888๋ฒˆ: ์—ฐ์‚ฐ์ž ๋ผ์›Œ๋„ฃ๊ธฐ

์ฒซ์งธ ์ค„์— ์ˆ˜์˜ ๊ฐœ์ˆ˜ N(2 ≤ N ≤ 11)๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” A1, A2, ..., AN์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ Ai ≤ 100) ์…‹์งธ ์ค„์—๋Š” ํ•ฉ์ด N-1์ธ 4๊ฐœ์˜ ์ •์ˆ˜๊ฐ€ ์ฃผ์–ด์ง€๋Š”๋ฐ, ์ฐจ๋ก€๋Œ€๋กœ ๋ง์…ˆ(+)์˜ ๊ฐœ์ˆ˜, ๋บ„์…ˆ(-)์˜ ๊ฐœ์ˆ˜, ๊ณฑ

www.acmicpc.net


1. ๋ฌธ์ œ

N๊ฐœ์˜ ์ˆซ์ž๋“ค, ์—ฐ์‚ฐ์ž ๊ฐœ์ˆ˜๊ฐ€ ๊ฐ๊ฐ ์ฃผ์–ด์งˆ ๋•Œ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฒฐ๊ณผ๊ฐ’์˜ ์ตœ๋Œ“๊ฐ’๊ณผ ์ตœ์†Ÿ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค.

2. ํ’€์ด

๋ฐฑํŠธ๋ž˜ํ‚น ๋ฌธ์ œ์ด๋‹ค.

๊ฒฐ๊ณผ๊ฐ’์„ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋„˜๊ธฐ๋ฉด์„œ ๋‹ค์Œ ์ˆซ์ž์™€ ์—ฐ์‚ฐํ•ด์ฃผ์—ˆ๋‹ค.

์—ฐ์‚ฐ์ž 4๊ฐœ๋ฅผ ๋งค๋ฒˆ ํ•˜๋‚˜ํ•˜๋‚˜ ๊ฐœ์ˆ˜ ์ฒดํฌ๋ฅผ ํ•˜๋ฉด์„œ ๊ฐœ์ˆ˜๊ฐ€ ์žˆ๋Š” ๊ฒƒ๋ถ€ํ„ฐ +,-,*,/ ์ˆœ์„œ๋กœ ์—ฐ์‚ฐ์„ ํ•ด์ฃผ์—ˆ๋‹ค.

๋‹ค์Œ ์—ฐ์‚ฐ์œผ๋กœ ๋„˜์–ด๊ฐ€๋Š” dfs๋ฅผ ์‹คํ–‰ํ•˜๊ธฐ ์ „ oper[operIdx]--; ๋กœ ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ–ˆ๊ณ  dfs๊ฐ€ ๋๋‚œ ํ›„ oper[operIdx]++;๋กœ ์—ฐ์‚ฐ์ž ์‚ฌ์šฉ ๊ฐœ์ˆ˜๋ฅผ ๋‹ค์‹œ ๋Š˜๋ ค์ฃผ์—ˆ๋‹ค.

์—ฐ์‚ฐ์€ calculator ํ•จ์ˆ˜๋ฅผ ๋”ฐ๋กœ ๋นผ์„œ ๊ฑฐ๊ธฐ์„œ ์—ฐ์‚ฐ์„ ํ•ด์ฃผ์—ˆ๊ณ  ๋งˆ์ง€๋ง‰ ์ˆซ์ž๊นŒ์ง€ ์˜ค๊ฒŒ๋˜๋ฉด max, min์„ ๊ฐฑ์‹ ํ•ด์ฃผ์—ˆ๋‹ค.

 

3. ์ฝ”๋“œ

import java.io.*;
import java.util.*;

public class Main {
    
	static int N, max, min, nums[], opers[];
	
	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(br.readLine());
		nums = new int[N];
		opers = new int[4];
		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<4; i++) {
			opers[i] = Integer.parseInt(st.nextToken());
		}
		// ์ž…๋ ฅ ๋
		
		max = Integer.MIN_VALUE;
		min = Integer.MAX_VALUE;
		dfs(1, nums[0]);
		System.out.println(max);
		System.out.println(min);
	}
	
	static void dfs(int numIdx, int sum) {
		if (numIdx == N) {
			max = Math.max(max, sum);
			min = Math.min(min, sum);
			return;
		}
		
		for (int operIdx=0; operIdx<4; operIdx++) {
			if (opers[operIdx] > 0) {
				int res = calculator(sum, nums[numIdx], operIdx);
				
				opers[operIdx] -= 1;
				dfs(numIdx+1,  res);
				opers[operIdx] += 1;
			}
		}
	}
	
	static int calculator(int sum, int num, int oper) {
		int res = 0;
		switch(oper) {
		case 0: //+
			res = sum + num;
			break;
		case 1: //-
			res = sum - num;
			break;
		case 2: //*
			res = sum * num;
			break;
		case 3: // /
			res = sum / num;
			break;
		}
		return res;
	}
}

4. ์‚ฌ๋‹ด

์•„์นจ์— ํ‘ธ๋Š” ๋ฐฑํŠธ๋ž˜ํ‚น.. ํ’€์–ด์„œ ๋„ˆ๋ฌด ๋ฟŒ๋“ฏํ•˜๋‹ค.

์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณ ์ˆ˜๊ฐ€ ๋˜๊ณ ์‹ถ๋‹ค