[BOJ 16637] ๊ดํธ์ถ๊ฐํ๊ธฐ
1. ๋ฌธ์ : https://www.acmicpc.net/problem/16637
2. ํ์ด
๋ก์ง์ ์๊ฐ๋ฌ๋๋ฐ ๊ตฌํ์ด ์ด๋ ค์ ๋ ๋ฌธ์
์ฐ์ฐ์๋ฅผ ๋ด๋ ๋ฐฐ์ด์ ๋ฐ๋ก ๋นผ์คฌ์ผ๋ฉด ์๊ฐ๋ฌ์์๋
dfs๋ก ์์ ํ์ํ์ฌ max๊ฐ ์ ๋ฐ์ดํธ
3. ์ฝ๋
package baekjoon;
import java.util.*;
public class Main {
static int ans;
static ArrayList<Character> ops;
static ArrayList<Integer> nums;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
String input = sc.next();
ops = new ArrayList<>();
nums = new ArrayList<>();
for (int i = 0; i < N; i++) {
char c = input.charAt(i);
if (c == '+' || c == '-' || c == '*') {
ops.add(c);
continue;
}
nums.add(Character.getNumericValue(c));
}
ans = Integer.MIN_VALUE;
DFS(nums.get(0), 0);
System.out.println(ans);
}
// ์ฐ์ฐ
public static int calc(char op, int n1, int n2) {
switch (op) {
case '+':
return n1 + n2;
case '-':
return n1 - n2;
case '*':
return n1 * n2;
}
return -1;
}
// DFS
public static void DFS(int result, int opIdx) {
// ์ฃผ์ด์ง ์ฐ์ฐ์์ ๊ฐ์๋ฅผ ์ด๊ณผํ์์ ๊ฒฝ์ฐ.
if (opIdx >= ops.size()) {
ans = Math.max(ans, result);
return;
}
// ๊ดํธ๊ฐ ์๋ ๊ฒฝ์ฐ
int res1 = calc(ops.get(opIdx), result, nums.get(opIdx + 1));
DFS(res1, opIdx + 1);
// ๊ดํธ๊ฐ ์๋ ๊ฒฝ์ฐ
if (opIdx + 1 < ops.size()) {
// result์ ์ค๋ฅธ์ชฝ์ ์๋ ๊ฐ์ ์ฐ์ฐํจ.
int res2 = calc(ops.get(opIdx + 1), nums.get(opIdx + 1), nums.get(opIdx + 2));
res2 = calc(ops.get(opIdx), result, res2);
// ํ์ฌ result์ ๋ฐฉ๊ธ ๊ตฌํ ๊ดํธ ๊ฐ์ ์ฐ์ฐํ ๊ฒฐ๊ณผ์ ๊ดํธ ์ค๋ฅธ์ชฝ์ ์กด์ฌํ๋ ์ฐ์ฐ์์ ์ธ๋ฑ์ค๋ฅผ ๋๊น.
DFS(res2, opIdx + 2);
}
}
}
'๐ป Coding Problems Solving > Brute Force' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ 1992] ์ฟผ๋ํธ๋ฆฌ (0) | 2023.06.26 |
---|---|
[BOJ 12919] A์ B2 (0) | 2023.06.18 |
[BOJ 3085] ์ฌํ๊ฒ์ (0) | 2022.06.26 |
[BOJ 2309] ์ผ๊ณฑ ๋์์ด (0) | 2022.06.21 |
[ํ๋ก๊ทธ๋๋จธ์ค] LV.2 ์นดํซ (0) | 2022.04.16 |
์ต๊ทผ๋๊ธ