반응형
https://www.acmicpc.net/problem/16637
16637번: 괄호 추가하기
길이가 N인 수식이 있다. 수식은 0보다 크거나 같고, 9보다 작거나 같은 정수와 연산자(+, -, ×)로 이루어져 있다. 연산자 우선순위는 모두 동일하기 때문에, 수식을 계산할 때는 왼쪽에서부터 순서대로 계산해야 한다. 예를 들어, 3+8×7-9×2의 결과는 136이다. 수식에 괄호를 추가하면, 괄호 안에 들어있는 식은 먼저 계산해야 한다. 단, 괄호 안에는 연산자가 하나만 들어 있어야 한다. 예를 들어, 3+8×7-9×2에 괄호를 3+(8×7)-(9×
www.acmicpc.net
package com.ssay.algo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class B16637 {
static boolean check[];
static int N;
static char[] arr;
static int maxValue;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
arr = br.readLine().toCharArray();
check = new boolean[N];
maxValue = Integer.MIN_VALUE;
DFS(0);
System.out.println(maxValue);
}
public static void DFS(int start) {
String[] result = new String[N];
int cnt = 0;
for (int i = 0; i < N; i++) {
if (check[i]) {
int tmp = 0;
if (arr[i + 1] == '+') {
tmp = (arr[i] - '0') + (arr[i + 2] - '0');
} else if (arr[i + 1] == '*') {
tmp = (arr[i] - '0') * (arr[i + 2] - '0');
} else if (arr[i + 1] == '-') {
tmp = (arr[i] - '0') - (arr[i + 2] - '0');
}
result[cnt++] = String.valueOf(tmp);
i += 2;
} else {
result[cnt++] = String.valueOf(arr[i]);
}
}
int sum = Integer.parseInt(result[0]);
for (int n = 1; n < cnt - 1; n = n + 2) {
if (result[n].charAt(0) == '+') {
sum = sum + Integer.parseInt(result[n+1]);
} else if (result[n].charAt(0) == '*') {
sum = sum * Integer.parseInt(result[n+1]);
} else if (result[n].charAt(0) == '-') {
sum = sum - Integer.parseInt(result[n+1]);
}
}
if (maxValue < sum) {
maxValue = sum;
}
for (int i = start; i < N - 2; i += 2) {
check[i] = true;
DFS(i + 4);
check[i] = false;
}
}
}
반응형
'ProgramSoliving' 카테고리의 다른 글
백준 : 2842 JAVA (2) | 2020.02.15 |
---|---|
백준 : 11279 (0) | 2020.02.09 |
백준 : 17471 (0) | 2020.02.09 |
백준 : 6593 (0) | 2020.02.08 |
백준 : 1504 (0) | 2020.02.08 |