본문 바로가기
알고리즘/BOJ(백준)

[ BOJ / Stack ] 후위 표기식2

by 뎁꼼 2020. 7. 11.

1. 문제


 

 

1935번: 후위 표기식2

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

www.acmicpc.net

 

2. 소스코드


- 간단한 후위표기식 문제에서, 치환만 추가된 문제.

- 치환을 위해 배열을 하나 생성하고, 해당 배열에 치환 값을 저장했다.

- map을 써도 된다. 메모리상으론 map이 더 효율적이다.

 

소스코드

#include <iostream>
#include <string>
#include <stack>
using namespace std;
int n , LUT[92];

double calPost(string str) {
	int size = str.size();
	stack<double> nums;
	for (int i = 0; i < size; ++i) {
		if (str[i] >= 'A' and str[i] <= 'Z') {
			nums.push(LUT[str[i]]);
		}
		else {
			char oper = str[i];
			double second = nums.top(); nums.pop();
			double first = nums.top(); nums.pop();
			switch (oper)
			{
			case '-': nums.push(first - second); break;
			case '+': nums.push(first + second); break;
			case '*': nums.push(first * second); break;
			case '/': nums.push(first / second); break;
			}
		}
	}
	return nums.top();
}

int main() {
	cin >> n;

	string postStr;
	cin >> postStr;

	for (int i = 0; i < n; ++i) {
		int temp;
		cin >> temp;
		LUT[(int)'A' + i] = temp;
	}
	
	double answer = calPost(postStr);
	cout << fixed;
	cout.precision(2);
	cout << answer << '\n';
	return 0;
}