관리 메뉴

풀이 보관함

[C++] 백준 1935번: 후기 표기식2 본문

problem solving/백준

[C++] 백준 1935번: 후기 표기식2

viin 2022. 7. 1. 19:36

문제

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

풀이 

스택으로 풀었다. calcultor() 안에 a와 b 연산 순서 확인

AA+A-라고 낼수도 있으니까 A 문자열이 어떤 숫자를 대입해야하는지도 저장하고 있어야 한다. 

소스

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

double calculator(double a, double b, char op)
{
    if(op == '+') return a + b;
    else if(op == '-') return b - a;
    else if(op == '/') return b / a;
    else if(op == '*') return a * b;
}

int main()
{
    int N = 0, result = 0;
    std::string str;
    double nums[27];
    std::stack<double> stk;

    std::cin >> N >> str;
    for(int i =0; i< N; ++i)
    {
        std::cin >> nums[i];
    }


    int idx = 0;
    for(int i =0; i <str.length(); ++i)
    {
        char c = str[i];
        if(65 <= c && c <= 90)
        {
            stk.push(nums[c-65]);
        }
        else
        {
            double a = stk.top(); stk.pop();
            double b = stk.top(); stk.pop();
            stk.push(calculator(a, b, c));
        }
    }

    printf("%0.2lf", stk.top());
    return 0;

}