ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 백준 1935 - 후위 표기식2
    백준 algorithm 2020. 3. 8. 02:02

    문제 설명

     

     

     

    => 피연산자들은 stack에 차례로 쌓은 후, 연산자를 만나면 해당 연산 작업을 한 후 다시 스택에 쌓는다. 

    => 여기서 주의해야할 점은

    stack top 아래 +-*/(연산자) stack top

    순서라는 것을 간과해서는 안된다. 

     

    =>피연산자들을 stack에 쌓기 위해서는 숫자배열에 접근하여야하는데, 이때 후위연산식에서 A, B , C 등의 아스키코드를 이용하여 인덱스 접근을 할 수 있다. 

    ***본이은 이 부분에서 한시간을 넘게 소비하였다. 

     

     

    #include <iostream>
    #include <stack>
    #include <string>
    #include <vector>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        ios_base::sync_with_stdio(false);
        cin.tie(nullptr);
        cout.tie(nullptr);
        
        int N;
        cin >> N;
        
        string s;
        cin>>s;
        
        vector<double> var(N);
        for(int i=0; i<N; ++i)
        {
            cin>>var[i];
        }
        
        int size=s.size();
        
        stack<double> st;
        
        for(int i=0; i<size; ++i)
        {
            if(s[i]=='+')
            {
                double tmp=st.top();
                st.pop();
                st.top()+=tmp;
            }
            else if(s[i] =='-')
            {
                double tmp=st.top();
                st.pop();
                st.top()-=tmp;
            }
            else if(s[i] =='*')
            {
                double tmp=st.top();
                st.pop();
                st.top()*=tmp;
            }
            else if(s[i] =='/')
            {
                double tmp=st.top();
                st.pop();
                st.top()/=tmp;
            }
            else//case char is number
            {
                st.push(var[s[i]-'A']);
            }
        }
        
        double answer=st.top();
        printf("%.2f\n", answer);
        
        return 0;
    }
    
    

    '백준 algorithm' 카테고리의 다른 글

    백준 5622 - 다이얼  (0) 2020.03.08
    백준 1918 - 후위 표기식  (0) 2020.03.08
    백준 5543- 상근날드  (0) 2020.03.05
    백준 18298 - 오큰수  (0) 2020.03.05
    백준 10799 - 쇠막대기  (0) 2020.03.03

    댓글

Designed by Who.