https://www.acmicpc.net/problem/14888
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. ์ฌ๋ด
์์นจ์ ํธ๋ ๋ฐฑํธ๋ํน.. ํ์ด์ ๋๋ฌด ๋ฟ๋ฏํ๋ค.
์๊ณ ๋ฆฌ์ฆ ๊ณ ์๊ฐ ๋๊ณ ์ถ๋ค
'Algorithm > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ] 14890 ๊ฒฝ์ฌ๋ก - Java (1) | 2023.10.24 |
---|---|
[BOJ] 14889 ์คํํธ์ ๋งํฌ - Java (0) | 2023.10.19 |
[BOJ] 14500 ํ ํธ๋ก๋ฏธ๋ ธ - Java (1) | 2023.10.18 |
[BOJ] 14499 ์ฃผ์ฌ์ ๊ตด๋ฆฌ๊ธฐ - Java (1) | 2023.10.17 |
[BOJ] 21610 ๋ง๋ฒ์ฌ ์์ด์ ๋น๋ฐ๋ผ๊ธฐ - Java (0) | 2023.10.14 |