2021년 9월 9일 목요일 22시
백준_16637_괄호추가하기_ 삼성 SW A형
https://www.acmicpc.net/problem/16637
16637번: 괄호 추가하기
첫째 줄에 수식의 길이 N(1 ≤ N ≤ 19)가 주어진다. 둘째 줄에는 수식이 주어진다. 수식에 포함된 정수는 모두 0보다 크거나 같고, 9보다 작거나 같다. 문자열은 정수로 시작하고, 연산자와 정수가
www.acmicpc.net
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
public class Main {
static int ans;
static ArrayList<Character> ops;
static ArrayList<Integer> nums;
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
int N = Integer.parseInt(br.readLine());
String input = br.readLine();
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);
bw.write(ans + "\n");
bw.flush();
bw.close();
bw.close();
}
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;
}
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()) {
int res2 = calc(ops.get(opIdx+1), nums.get(opIdx+1), nums.get(opIdx+2));
DFS(calc(ops.get(opIdx), result, res2), opIdx +2);
}
}
}
<참고>
https://steady-coding.tistory.com/36
[BOJ] 백준 16637번 : 괄호 추가하기 (JAVA)
문제의 링크 : https://www.acmicpc.net/problem/16637 16637번: 괄호 추가하기 첫째 줄에 수식의 길이 N(1 ≤ N ≤ 19)가 주어진다. 둘째 줄에는 수식이 주어진다. 수식에 포함된 정수는 모두 0보다 크거나 같고,
steady-coding.tistory.com
'알고리즘 > 백준' 카테고리의 다른 글
백준_17281_야구_ 삼성 SW A형 (0) | 2021.09.24 |
---|---|
백준_17136_색종이 붙이기_ 삼성 SW A형 (0) | 2021.09.24 |
백준_17135_캐슬디펜스_ 삼성 SW A형 (0) | 2021.09.11 |
백준_17070_파이프옮기기_ 삼성 SW A형 (0) | 2021.09.09 |
백준_13460_구슬 탈출 2 (0) | 2021.09.06 |