1일1알

백준 1935번 후위 표기식2 C++ 본문

알고리즘

백준 1935번 후위 표기식2 C++

영춘권의달인 2023. 3. 11. 12:58

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

 

1935번: 후위 표기식2

첫째 줄에 피연산자의 개수(1 ≤ N ≤ 26) 가 주어진다. 그리고 둘째 줄에는 후위 표기식이 주어진다. (여기서 피연산자는 A~Z의 영대문자이며, A부터 순서대로 N개의 영대문자만이 사용되며, 길이

www.acmicpc.net

 

스택 사용, float가 아닌 double 사용해야 함.

 

#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>

using namespace std;
using int64 = long long;

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

	int n;
	string str;
	cin >> n >> str;
	map<char, double> m;
	for (int i = 0; i < n; i++) {
		int val;
		cin >> val;
		m['A' + i] = val;
	}
	stack <double> st;
	for (int i = 0; i < str.length(); i++) {
		if (str[i] == '*' || str[i] == '+' || str[i] == '/' || str[i] == '-') continue;
		str[i] = m[str[i]];
	}
	for (int i = 0; i < str.length(); i++) {
		if (str[i] == '*' || str[i] == '+' || str[i] == '/' || str[i] == '-') {
			double val1 = st.top();
			st.pop();
			double val2 = st.top();
			st.pop();
			double val;
			switch (str[i]) {
			case '*':
				val = val2 * val1;
				break;
			case '+':
				val = val2 + val1;
				break;
			case '/':
				val = val2 / val1;
				break;
			case '-':
				val = val2 - val1;
				break;
			}
			st.push(val);
		}
		else {
			double val = (int)str[i];
			st.push(val);
		}
	}
	cout << fixed;
	cout.precision(2);
	cout << st.top();
};

'알고리즘' 카테고리의 다른 글

백준 21318번 피아노 체조 C++  (0) 2023.03.14
백준 3758번 KCPC C++  (0) 2023.03.12
백준 16168번 퍼레이드 C++  (0) 2023.03.08
백준 16398번 행성 연결 C++  (0) 2023.03.07
백준 1411번 비슷한 단어 C++  (0) 2023.03.05