넘치게 채우기
[BOJ] 6514: Expressions 본문
https://www.acmicpc.net/problem/6514
BOJ - Expressions
문제 유형: 스택, 큐, 트리
문제 난이도: Silver I
시간 제한: 1초
메모리 제한: 128MB
문제
Arithmetic expressions are usually written with the operators in between the two operands (which is called infix notation). For example, (x+y)*(z-w) is an arithmetic expression in infix notation. However, it is easier to write a program to evaluate an expression if the expression is written in postfix notation (also known as reverse polish notation). In postfix notation, an operator is written behind its two operands, which may be expressions themselves. For example, x y + z w - * is a postfix notation of the arithmetic expression given above. Note that in this case parentheses are not required.
To evaluate an expression written in postfix notation, an algorithm operating on a stack can be used. A stack is a data structure which supports two operations:
- push: a number is inserted at the top of the stack.
- pop: the number from the top of the stack is taken out.
During the evaluation, we process the expression from left to right. If we encounter a number, we push it onto the stack. If we encounter an operator, we pop the first two numbers from the stack, apply the operator on them, and push the result back onto the stack. More specifically, the following pseudocode shows how to handle the case when we encounter an operator O:
a := pop();
b := pop();
push(b O a);
The result of the expression will be left as the only number on the stack.
Now imagine that we use a queue instead of the stack. A queue also has a push and pop operation, but their meaning is different:
- push: a number is inserted at the end of the queue.
- pop: the number from the front of the queue is taken out of the queue.
Can you rewrite the given expression such that the result of the algorithm using the queue is the same as the result of the original expression evaluated using the algorithm with the stack?
스택으로 후위표기식을 푸는 것에서 스택 대신 큐를 써서 같은 결과를 만들어내도록 수식을 변형할 수 있나요?
입력
The first line of the input contains a number T (T ≤ 200). The following T lines each contain one expression in postfix notation. Arithmetic operators are represented by uppercase letters, numbers are represented by lowercase letters. You may assume that the length of each expression is less than 10000 characters.
테스트케이스의 개수 T가 주어집니다.
아래의 T개의 줄마다각 후위표기 수식이 주어집니다. 대문자는 연산자, 소문자는 오퍼랜드란 뜻입니다.
출력
For each given expression, print the expression with the equivalent result when using the algorithm with the queue instead of the stack. To make the solution unique, you are not allowed to assume that the operators are associative or commutative.
각 수식을 후휘표기법에서의 연산 순서에서 스택 대신 큐를 쓸 때 같은 결과로 얻을 수 있도록 변환한 수식을 만드시오.
풀이
주어진 후위 표기식을 파싱하면서, 이진 트리로 변환한다.
리프 노드에는 오퍼랜드들이, 루트 및 중간 노드들에는 연산자들이 있게 한다.
위 그림을 보다시피, 정답을 구하려면, 변환된 이진트리를 bfs로 순회하여 한 줄의 문자열로 변환시킨 뒤, 그 문자열을 뒤집어서 반환해주면 된다.
코드
C++
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
char val;
TreeNode *left;
TreeNode *right;
TreeNode(char val) {
this->val = val;
left = NULL;
right = NULL;
}
};
string traverse(TreeNode *root) {
string ans;
queue<TreeNode *> q;
q.push(root);
while (!q.empty()) {
auto curr = q.front();
q.pop();
if (curr->left)
q.push(curr->left);
if (curr->right)
q.push(curr->right);
ans += curr->val;
}
reverse(ans.begin(), ans.end());
return ans;
}
void solve() {
string exp;
cin >> exp;
stack<TreeNode *> st;
for (const auto &ch : exp) {
if (islower(ch)) {
st.push(new TreeNode(ch));
} else {
auto node = new TreeNode(ch);
auto opB = st.top();
st.pop();
auto opA = st.top();
st.pop();
node->left = opA;
node->right = opB;
st.push(node);
}
}
auto root = st.top();
st.pop();
cout << traverse(root) << "\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
int t;
cin >> t;
while (t--) {
solve();
}
return 0;
}
'PS > BOJ' 카테고리의 다른 글
[BOJ] 4042 : Vampires! (0) | 2024.10.08 |
---|---|
[BOJ] 2403: 게시판 구멍 가리기 (0) | 2024.10.07 |
[BOJ] 자바의 형변환 (0) | 2024.10.03 |
[BOJ] 2942: 퍼거슨과 사과 (0) | 2024.10.02 |
[BOJ] 25342: 최대 최소공배수 (0) | 2024.09.26 |