백준 1935번 후위 표기식2
문제
후위 표기식과 각 피연산자에 대응하는 값들이 주어져 있을 때, 그 식을 계산하는 프로그램을 작성하시오.
문제풀이
사용한 알고리즘 : 구현(1) 코드 17~50
입력으로 주어진 후위 표기식 순서대로 계산해주면 됩니다.1. 알파벳이면 stack 에 저장하고,
2. 연산이면 계산합니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
using namespace std; | |
typedef pair<int, int> pii; | |
int N; | |
double arr[30]; | |
string St; | |
stack<double> S; | |
int main() {ios_base::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL); | |
cin >> N; | |
cin >> St; | |
for (int i = 0; i < N; ++i) | |
cin >> arr[i]; | |
for (int i = 0; i < St.size(); ++i) { | |
// 사칙연산인 경우 | |
if (St[i] == '*') { | |
double a = S.top(); | |
S.pop(); | |
double b = S.top(); | |
S.pop(); | |
S.push(b * a); | |
} | |
else if (St[i] == '+') { | |
double a = S.top(); | |
S.pop(); | |
double b = S.top(); | |
S.pop(); | |
S.push(b + a); | |
} | |
else if (St[i] == '-') { | |
double a = S.top(); | |
S.pop(); | |
double b = S.top(); | |
S.pop(); | |
S.push(b - a); | |
} | |
else if (St[i] == '/') { | |
double a = S.top(); | |
S.pop(); | |
double b = S.top(); | |
S.pop(); | |
S.push(b / a); | |
} | |
// 알파벳인 경우 | |
else | |
S.push(arr[St[i] - 'A']); | |
} | |
cout << fixed; | |
cout.precision(2); | |
cout << S.top() << '\n'; | |
return 0; | |
} |
댓글
댓글 쓰기
긴 글 읽어주셔서 감사합니다.
궁금한게 있으시다면 댓글 달아주세요!