[boj] (s3) 1935 후위표기식

강신현·2022년 4월 2일
0

✅ stack

문제

링크

풀이

후위 표기식의 연산자의 이전 두 수를 연산하는 과정을 반복한다. 따라서 숫자일 경우 저장해두고 연산자일 경우 이전 두 수의 연산값을 저장해야 하기 때문에 stack을 사용했다.

코드

#include <iostream>
#include <algorithm>
#include <string>
#include <stack>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    stack<double> st;

    int n;
    string str;
    cin >> n >> str;

    int num[n];
    for(int i=0;i<n;i++){
        cin >> num[i];
    }

    for(int i=0;i<str.length();i++){
        if(str[i] >= 'A' && str[i] <= 'Z'){ // 피연산자일때
            int idx = str[i]-'A';
            st.push(num[idx]);
        }
        else{ // 연산자일때
            double a, b;
            b = st.top();
            st.pop();
            a = st.top();
            st.pop();

            if(str[i] == '+') st.push(a+b);
            if(str[i] == '-') st.push(a-b);
            if(str[i] == '*') st.push(a*b);
            if(str[i] == '/') st.push(a/b);
        }
    }

    cout << fixed;
    cout.precision(2);

    cout << st.top() << "\n";

    return 0;
}
profile
땅콩의 모험 (server)

0개의 댓글