[BOJ] - 1935. 후위 표기식2 [스택] - c++

ha·2022년 2월 9일
0

BOJ

목록 보기
27/28

https://www.acmicpc.net/problem/1935

c++ 후위표기식(스택)풀이
알파벳 ABCDE...순서대로 정수값 mapping
주어진 식 알파벳 만날때 마다 매핑되는 숫자 스택에 push(alphabet[c-'A'])
부호 만나는 경우 stack top 2개 pop , pop한 순서 주의

#include <iostream>
#include <string>
#include <functional>
#include <stack>
#include <vector>
using namespace std;
int N;
string s;
vector<int> alphabet(26);
int main() {
    cin>>N;
    cin>>s;
    for(int i=0;i<N;i++)
    {
        cin>>alphabet[i];   
    }
    stack<double> st;
    for(auto c : s)
    {
        if(c>='A' && c<='Z')
        {
            st.push(alphabet[c-'A']);
        }
        else
        {
            if (!st.empty())
            {
            double b = st.top(); st.pop();
            double a = st.top(); st.pop();
            double tmp =0;
            if(c=='+') tmp=a+b;
            else if(c=='-') tmp=a-b;
            else if(c=='/') tmp = a/b;
            else if(c=='*') tmp = a*b;
            st.push(tmp);
            //cout << tmp<<"()";
            }
        }
    }
    cout << fixed;
	cout.precision(2);
	cout << st.top() << '\n';
	return 0;
}

0개의 댓글