๋ฌธ์ (์ถ์ฒ: https://www.acmicpc.net/problem/9523)
< Arithmetic with Morse >
๋ฌธ์ ํ์ด
1) ๋ชจ์ค ๋ถํธ๋ฅผ ์ซ์๋ก ๋ฐ๊พธ๊ธฐ
2) ๊ณฑ์
3) ๋ํ๊ธฐ
์์ผ๋ก ๋ชจ์ค ํํ์์ ์ซ์๋ก ๊ตฌํ๋ค.
my solution (Java)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Stack;
public class _9523_ { // Arithmetic with Morse
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
int N = Integer.parseInt(bf.readLine());
String str = bf.readLine();
str = str.replace(" ", "");
Stack<String> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '.') {
int num = 0;
if (stack.size() > 0 && !stack.peek().equals("+") && !stack.peek().equals("*")) {
num = Integer.parseInt(stack.pop());
}
stack.add(Integer.toString(num + 1));
} else if (str.charAt(i) == '-') {
int num = 0;
if (stack.size() > 0 && !stack.peek().equals("+") && !stack.peek().equals("*")) {
num = Integer.parseInt(stack.pop());
}
stack.add(Integer.toString(num + 5));
} else if (str.charAt(i) == ':') {
int num = 0;
if (stack.size() > 0 && !stack.peek().equals("+") && !stack.peek().equals("*")) {
num = Integer.parseInt(stack.pop());
}
stack.add(Integer.toString(num + 2));
} else if (str.charAt(i) == '=') {
int num = 0;
if (stack.size() > 0 && !stack.peek().equals("+") && !stack.peek().equals("*")) {
num = Integer.parseInt(stack.pop());
}
stack.add(Integer.toString(num + 10));
} else {
stack.add(Character.toString(str.charAt(i)));
}
}
Stack<Integer> result = new Stack<>();
int a = Integer.parseInt(stack.pop());
while (!stack.isEmpty()) {
String temp = stack.pop();
int b = Integer.parseInt(stack.pop());
if (temp.equals("+")) {
result.add(a);
result.add(b);
} else if (temp.equals("*")) {
result.add(a * b);
}
a = result.pop();
}
int answer = a;
while (!result.isEmpty()) {
answer += result.pop();
}
System.out.println(answer);
}
}
๋ณ์)
N : ์ฐ์ฐ์ ์
str : ๋ชจ์ค ํํ์
stack : ๋ชจ์ค ๋ฌธ์๋ฅผ ์ซ์๋ก ๋ณํํ ๊ฐ์ ์ ์ฅ
result : ๊ณฑํ๊ธฐ ๊ณ์ฐํ ๊ฐ์ ์ ์ฅ
answer : ์ต์ข ๋ชจ์ค ํํ์ ๊ฐ
์ฐ์ฐ์ ์์ ๋ชจ์ค ํํ์์ ์ ๋ ฅ๋ฐ๋๋ค. ๋ชจ์ค ํํ์์์ ๊ณต๋ฐฑ์ ์ ๊ฑฐํ๊ณ ์์ฐจ ํ์ํ๋ฉฐ ๋ชจ์ค ๋ฌธ์๋ฅผ ์ซ์๋ก ๋ณํํ์ฌ stack์ ์ ์ฅํ๋ค. ์ด๋, ๋ํ๊ธฐ์ ๊ณฑ์ ํ์๋ ๋ณํ ์์ด ๊ทธ๋๋ก stack์ ์ ์ฅํ๋ค.
stack์ ์๋ ๊ฐ์ pop ํ๋ฉด์ ๊ณฑ์ ์ฐ์ฐ์๊ฐ ์์ ๋ ๊ณฑ์ ๊ณ์ฐ ํ result stack์ ์ ์ฅํ๋ค. ์ต์ข result stack์ ์๋ ๊ฐ๋ค์ ๋ค ๋ํ ํ ์ถ๋ ฅํ๋ค.
'๐Algorithm > ๐ฅBaekjoon' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Baekjoon] 17585_Circuit Math (2) | 2025.07.17 |
---|---|
[Baekjoon] 8594_Program (0) | 2025.07.16 |
[Baekjoon] 14210_Kartomat (0) | 2025.07.14 |
[Baekjoon] 27060_Vertical Histogram (2) | 2025.07.11 |
[Baekjoon] 32076_Easy as ABC (2) | 2025.07.10 |