Algorithm/BOJ
[BOJ] 괄호 추가하기
goakgoak
2020. 8. 26. 18:19
[16337] 괄호 추가하기
https://www.acmicpc.net/problem/16637
- 길이가 N인 수식이 주어진다. N은 1-9 숫자 혹은 {+, -, *} 연산자
- 연산자 우선순위는 모두 동일. 왼쪽부터 순서대로 계산
- 단 괄호를 추가했을 때는 괄호 안 수식 먼저 계산하여 중첩 괄호는 허용하지 않는다.
- 수식이 주어졌을 때, 괄호를 적절히 추가하여 식의 결과의 최댓값 구하는 문제
- 괄호의 수는 제한이 없으며 없어도 된다.
- 수식 길이 N(1<=N<=19, 홀수)
Solution
- 수식에 괄호를 추가하는 것 => 먼저 계산하는 것 => 먼저 계산할 수식을 고르는 것
- 연산자는 최대 9개가 나올 수 있고, 9개를 모두 고르는 일 => 괄호가 하나도 없을 때
- 괄호는 중첩될 수 없으므로 ((3 ①+ 8) ②* 7) ③- 9 ④+ 2 의 ①, ② 연산자를 연속해서 뽑을 수 없다.
- 위 예에서는 1번 연산자를 뽑는 경우(먼저 계산하는 경우)에는 최소 3번째 연산자부터 괄호를 넣을 수 있다.
- permutation()을 돌려 괄호를 추가할 때 마다 priority 리스트에 추가하고 해당 연산자를 먼저 계산한 다음 (=> 1번 calc()) 나머지 연산을 이어서 계산한다(=> 2번 calc()).
소스코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Main {
static int n, max;
static char origin[];
static int copy[];
static List<Integer> priority;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.valueOf(br.readLine());
origin = br.readLine().toCharArray();
priority = new ArrayList<>();
max = solve();
permutation(0, 1);
System.out.println(max);
}
static void permutation(int depth, int start) {
for (int i = start; i < n; i += 2) {
priority.add(i);
max = Math.max(max, solve());
permutation(depth + 1, i + 4);
priority.remove(depth);
}
}
static int solve() {
copyExpression();
for (int i : priority) {
calc(i, origin[i]);
}
return calc();
}
static int calc() { // 2
int result = copy[0];
for (int i = 1; i < n; i += 2) {
if (copy[i] < 0)
continue;
switch (origin[i]) {
case '+':
result += copy[i+1];
break;
case '-':
result -= copy[i+1];
break;
case '*':
result *= copy[i+1];
break;
}
}
return result;
}
static void calc(int idx, char op) { // 1
switch (op) {
case '+':
copy[idx - 1] += copy[idx + 1];
copy[idx] = -1;
break;
case '-':
copy[idx - 1] -= copy[idx + 1];
copy[idx] = -1;
break;
case '*':
copy[idx - 1] *= copy[idx + 1];
copy[idx] = -1;
break;
}
}
static void copyExpression() {
copy = new int[n];
for (int i = 0; i < n; i++) {
if (Character.isDigit(origin[i])) {
copy[i] = origin[i] - '0';
}
}
}
}
|
cs |