https://www.acmicpc.net/problem/1935
1935번: 후위 표기식2
첫째 줄에 피연산자의 개수(1 ≤ N ≤ 26) 가 주어진다. 그리고 둘째 줄에는 후위 표기식이 주어진다. (여기서 피연산자는 A~Z의 영대문자이며, A부터 순서대로 N개의 영대문자만이 사용되며, 길이
www.acmicpc.net
후위 표기식이 주어졌을 때 이를 계산하는 문제이다.
스택을 만들고 연산기호( * , / , + , - )가 오는 경우는 위에서 두개를 계산하고 push 그 외에는 그냥 push해주면 된다.
코드
#include <iostream>
#include <string>
#include <vector>
#include <stack>
#define ch 65
using namespace std;
string s;
double alpa[26];
int main(){
int N; cin>>N;
cin>>s;
for(int i=0;i<N;i++) cin>>alpa[i];
stack<double> st;
for(int i=0;i<s.size();i++){
if(s[i]=='+'||s[i]=='-'||s[i]=='/'||s[i]=='*'){
double a2=st.top();
st.pop();
double a1=st.top();
st.pop();
if(s[i]=='+') st.push(a1+a2);
else if(s[i]=='-') st.push(a1-a2);
else if(s[i]=='*') st.push(a1*a2);
else if(s[i]=='/') st.push(a1/a2);
}else{
st.push(alpa[int(s[i])-ch]);
}
}
cout<<fixed;
cout.precision(2);
cout<<st.top();
return 0;
}
'백준 > Tree' 카테고리의 다른 글
[BOJ] 19581 두 번째 트리의 지름 C++ (0) | 2021.08.09 |
---|---|
[BOJ] 1167 트리의 지름 C++ (0) | 2021.08.09 |
[BOJ] 1655 가운데를 말해요 C++ (0) | 2021.08.05 |
[BOJ] 1918 후위표기식 C++ (0) | 2021.08.04 |
[BOJ] 2263 트리의 순회 C++ (0) | 2021.08.04 |