Computer Science/Algorithm Problem

백준] 2504 - 괄호의 값(KOI 2008 지역본선)

TwinParadox 2018. 5. 24. 12:03
728x90

시간 제한 : 1초

메모리 제한 : 128MB




입력

첫째 줄에 괄호열을 나타내는 문자열(스트링)이 주어진다. 단 그 길이는 1 이상, 30 이하이다.




출력

첫째 줄에 그 괄호열의 값을 나타내는 정수를 출력한다. 만일 입력이 올바르지 못한 괄호열이면 반드시 0을 출력해야 한다.




소스코드

#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
int main(void)
{
	char arr[32];
	stack<char> st;
	int tmp = 1, sum = 0;
	bool wrong = false;

	cin >> arr;
	for (int i = 0; arr[i]; i++)
	{
		if (arr[i] == '(')
		{
			tmp *= 2;
			st.push('(');
		}
		else if (arr[i] == '[')
		{
			tmp *= 3;
			st.push('[');
		}
		else if (arr[i] == ')')
		{
			if (arr[i - 1] == '(')
				sum += tmp;
			if (st.empty())
			{
				wrong = true;
				break;
			}
			if (st.top() == '(')
				st.pop();
			tmp /= 2;
		}
		else
		{
			if (arr[i - 1] == '[')
				sum += tmp;
			if (st.empty())
			{
				wrong = true;
				break;
			}
			if (st.top() == '[')
				st.pop();
			tmp /= 3;
		}
	}
	if (wrong || !st.empty())
		cout << 0;
	else
		cout << sum;
}




Tip

스택을 이용할 줄 알면 쉽게 풀 수 있는 문제였다. 다만, STL을 사용할 때 발생할 수 있는 런타임 에러에 대한 부분을 신경써야 한다.



728x90
728x90