※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※
이번에 볼 문제는 백준 11289번 문제인 Boolean Postfix이다.
문제는 아래 링크를 확인하자.
https://www.acmicpc.net/problem/11289
11289번: Boolean Postfix
Logical Boolean expressions are typically represented using infix notation, where the operators (∧, ∨) are placed between the operands. For example, ((a∧b)∨¬c) states that for the expression to be true, both a and b should be true, or c should be
www.acmicpc.net
bool 변수의 and, or, xor 및 not 연산을 지원하는 후위표기식의 계산을 구현하는 문제이다.
후위표기식의 계산은 스택 자료구조를 이용하면 아래와 같이 편하게 구현할 수 있다.
C++에서 and는 '&', or은 '|', xor은 '^'으로 표현한다는 점을 상기해 문제를 해결하자.
아래는 제출한 소스코드이다.
#include <iostream>
#include <stack>
using namespace std;
int T;
stack<bool> stk;
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> T;
while (T--) {
int N; cin >> N;
while (N--) {
char c; cin >> c;
if (c == '0') stk.push(0);
else if (c == '1') stk.push(1);
else if (c == 'A') {
bool x = stk.top(); stk.pop();
bool y = stk.top(); stk.pop();
stk.push(x & y);
}
else if (c == 'R') {
bool x = stk.top(); stk.pop();
bool y = stk.top(); stk.pop();
stk.push(x | y);
}
else if (c == 'X') {
bool x = stk.top(); stk.pop();
bool y = stk.top(); stk.pop();
stk.push(x ^ y);
}
else {
bool x = stk.top(); stk.pop();
stk.push(x ^ 1);
}
}
bool x = stk.top(); stk.pop();
cout << x << '\n';
}
}
728x90
'BOJ' 카테고리의 다른 글
[BOJ 26307 // C++] Correct (0) | 2022.12.13 |
---|---|
[BOJ 5212 // C++] 지구 온난화 (0) | 2022.12.13 |
[BOJ 24085 // C++] 希少な数 (Rare Number) (0) | 2022.12.13 |
[BOJ 11291 // C++] Alicia's Afternoon Amble (0) | 2022.12.13 |
[BOJ 26043 // C++] 식당 메뉴 (0) | 2022.12.12 |