티스토리 뷰

 

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

 

2504번: 괄호의 값

4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다.  만일

www.acmicpc.net

 

Stack STL를 활용하여 풀었습니다. 중요한 부분은 Check 부분인데, len 값과 bal.top()이 같을 경우에 더해주고, 나머지는 이미 더한 값이기 때문에 나눠줍니다. 이부분을 이해하는 것이 제일 중요했던 것 같습니다.

 

 

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

using namespace std;
stack<char> bal;
char len = 0;
int total = 0;
int tmp = 1;

void Check(int plus) {
	if (bal.top() == len) {
		total += tmp;
		tmp /= plus;
	}
	else {
		tmp /= plus;
	}
	bal.pop();
	len = 0;
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(nullptr);
	string s;
	getline(cin, s);
	for (auto c : s) {
		if (c == '(') {
			tmp *= 2;
			bal.push(c);
			len = c;
		}	
		else if(c == '[') {
			tmp *= 3;
			bal.push(c);
			len = c;
		}
		else if (c == ')') {
			if (bal.empty() || bal.top() != '(') {
				total = 0;
				break;
			}
			Check(2);
		}
		else if (c == ']') {
			if (bal.empty() || bal.top() != '[') {
				total = 0;
				break;
			}
			Check(3);
		}
	}
	if (!bal.empty())
		total = 0;
	cout << total << "\n";
}
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함