1
+ package week8 .괄호추가하기 ;
2
+
3
+ import java .io .BufferedReader ;
4
+ import java .io .IOException ;
5
+ import java .io .InputStreamReader ;
6
+ import java .util .ArrayList ;
7
+ import java .util .List ;
8
+ public class BOJ_16637 {
9
+ static int N ;
10
+ static int max ;
11
+ static List <Integer > nums ;
12
+ static List <Character > ops ;
13
+ public static void main (String [] args ) throws IOException {
14
+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
15
+ N = Integer .parseInt (br .readLine ());
16
+
17
+ String line = br .readLine ();
18
+ nums = new ArrayList <>();
19
+ ops = new ArrayList <>();
20
+ for (int i =0 ; i <line .length (); i ++){
21
+ char ch = line .charAt (i );
22
+ if (ch =='+' ||ch =='-' ||ch =='*' ){
23
+ ops .add (ch );
24
+ }else {
25
+ nums .add (Character .getNumericValue (ch ));
26
+ }
27
+ }
28
+
29
+ max = Integer .MIN_VALUE ;
30
+ dfs (nums .get (0 ), 0 );
31
+
32
+ System .out .println (max );
33
+ }
34
+
35
+ static int calc (int number1 , char op , int number2 ){
36
+ int result = 0 ;
37
+
38
+ switch (op ){
39
+ case '+' :
40
+ result = number1 +number2 ;
41
+ break ;
42
+ case '-' :
43
+ result = number1 -number2 ;
44
+ break ;
45
+ case '*' :
46
+ result = number1 *number2 ;
47
+ break ;
48
+ }
49
+
50
+ return result ;
51
+ }
52
+
53
+ static void dfs (int result , int opsIdx ){
54
+ if (opsIdx == ops .size ()){
55
+ max = Math .max (max , result );
56
+ return ;
57
+ }
58
+
59
+ //괄호가 없는 경우
60
+ dfs (calc (result , ops .get (opsIdx ), nums .get (opsIdx +1 )), opsIdx +1 );
61
+
62
+ //괄호가 있는 경우
63
+ if (opsIdx +1 <ops .size ()){
64
+ int res = calc (nums .get (opsIdx +1 ), ops .get (opsIdx +1 ), nums .get (opsIdx +2 ));
65
+ dfs (calc (result , ops .get (opsIdx ), res ), opsIdx +2 );
66
+ }
67
+ }
68
+ }
69
+ /**
70
+ * 백트래킹을 사용하여 괄호 없는 연산 수행 후 수식의 뒤에서 부터 괄호를 추가하여 연산을 한다
71
+ * max 값을 0으로 설정해두면 max값이 음수일 때 답이 틀린다
72
+ */
0 commit comments