# 유형 : 그래프 탐색, DFS

# 난이도 : 골드 3

# 설명은 주석을 통해 남겨두었음.

 

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
package bj;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class p16637 {
    static int N, maxValue = Integer.MIN_VALUE;
    static char arr[];
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        N = Integer.parseInt(br.readLine());
        arr = new char[N];
        String str = br.readLine();
        arr = str.toCharArray();
        dfs(1,arr[0]-'0',0false);
        System.out.println(maxValue);
    }
    
    // 괄호쳐서 계산하기 위한 previous값, 연속해서 괄호를 칠수 없으므로 이것을 체크하기 위한 imPossible, 
    private static void dfs(int index, int current, int previous, boolean imPossible) {
        // TODO Auto-generated method stub
        
        //마지막 인덱스 일때 Max값 비교
        if(index >= N) {
            maxValue = Math.max(maxValue, current);
            return;
        }
        
        // 괄호를 치지 않는다면 현재까지의 값을 계산해야하므로 next 변수에 저장, index+2인 이유는 인덱스는 2를 간격으로 배열에 저장되어있다.
        int next = cal(current, arr[index+1]-'0', arr[index]);
        dfs(index+2, next, current, false);
        
        //연산자 우선순위는 모두 동일하기 때문에, 수식을 계산할 때는 왼쪽에서부터 순서대로 계산해야 한다. 따라서 인덱스가 1일 경우에 괄호치는 것은 의미가 없다.
        // 괄호를 칠 때
        if(index>1 && !imPossible) {
            next = cal(arr[index-1]-'0',arr[index+1]-'0',arr[index]);
            dfs(index+2, cal(previous, next, arr[index-2]), 0true);
        }
    }
 
    static int cal(int a, int b, char ch) {
        if(ch == '+')
            return a+b;
        else if(ch == '-')
            return a-b;
        else
            return a*b;
    }
}
 
cs

+ Recent posts