• Home
  • About
    • 코드좀비 photo

      코드좀비

      An amazing website.

    • Learn More
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects

백준 2504 괄호의 값 C++

05 May 2019

Reading time ~1 minute

이번 문제는 백준 2504번 괄호의 값 입니다.

핵심요점

  • ( , [ 발견 -> 푸쉬

  • ), ] 발견 ->

(1) 스텍에서 위에가 ( 나 [ 가 나올때까지 (만약 스택이 empty가 되면 짝이 맞지 않음)

(2) tempSum 에 곱하여 팝

(3) (,[ 발견시 맨처음 ) ,] 와 짝이 맞는지 확인/ 안맞으면 오류

(4) 최종적으로 ) 와 ] 인지에 따라 *2, *3

(5) 그다음 앞이 숫자라면 또다시 숫자일때까지 덧셈

에시) (()[[]]) 스택 : ( -> (( -> (2 -> (2[ -> (2[[ -> (2[3 -> (29 -> (11 -> 22

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

using namespace std;

int main() {
	stack<string> st;
	string strings;
	string temp;
	int tempSum;
	int result = 1;
	cin >> strings;
	for (int i = 0; i < strings.size(); i++) {
		temp = strings.at(i);
		if (temp == "(" || temp == "[")
			st.push(temp);
		else {
			tempSum = 1;
			// (1)
			while (!st.empty() && st.top() != "(" && st.top() != "[") {
				//(2)
				tempSum *= stoi(st.top());
				st.pop();
			}
			// (3)
			if (st.empty() || (temp == ")" && st.top() != "(") || (temp == "]"&& st.top() != "[")) {
				result = 0;
				break; 
			}
			// (4)
			if (temp == ")")
				tempSum *= 2;
			else
				tempSum *= 3;
			st.pop();
			// (5)
			while (!st.empty() && st.top() != "(" && st.top() != "[") {
				tempSum += stoi(st.top());
				st.pop();
			}
			st.push(to_string(tempSum));
		}
	}
	if (result == 0 || st.size()!=1 || st.top()=="[" || st.top()=="(" )
		cout << 0;
	else
		cout << st.top();

	return 0;
}


백준C++ Share Tweet +1