알고리즘/백준
백준 2504 괄호의 값
등반
2021. 12. 25. 23:52
https://www.acmicpc.net/problem/2504
2504번: 괄호의 값
4개의 기호 ‘(’, ‘)’, ‘[’, ‘]’를 이용해서 만들어지는 괄호열 중에서 올바른 괄호열이란 다음과 같이 정의된다. 한 쌍의 괄호로만 이루어진 ‘()’와 ‘[]’는 올바른 괄호열이다. 만일
www.acmicpc.net
1. 올바른 괄호인지 확인하기
2. 스택을 이용해서 괄호 계산하기
두가지를 해결하는 문제다.
한 번에 1, 2를 해결할 수 있지만, 본인은 역할을 구분하였다.
#include <iostream>
#define fio cin.tie(0)->sync_with_stdio(0)
using namespace std;
#include <stack>
#include <string>
bool is_stack_right(const string& S){
stack<char> check_right;
for(int s = 0; s < S.size(); s++){
char now = S[s];
if(now == '(' || now == '['){
check_right.push(now);
}else{
if(check_right.empty()) return false;
if(now ==')'){
if(check_right.top() == '('){
check_right.pop();
}else{
return false;
}
}else{// ']'
if(check_right.top() =='['){
check_right.pop();
}else{
return false;
}
}
}
}
if(!check_right.empty()) return false;
return true;
}
int main(){
fio;
string S; cin >> S;
//일단 올바른 문자열인지 확인
if(!is_stack_right(S)){
cout << 0;
return 0;
}
//이후는 올바른 문자열
//
stack<string> stack_;
for(int s = 0; s < S.size(); s++){
char now = S[s];
if(now == '(' || now == '['){
string tmp; tmp.push_back(now);
stack_.push(tmp);
}else{
if(now == ')'){
if(stack_.top() =="("){
stack_.pop();
stack_.push("2");
}else{
int sum = 0;
while(stack_.top() != "("){
sum += stoi(stack_.top());
stack_.pop();
}
stack_.pop();
stack_.push(to_string(2*sum));
}
}else{ // ]
if(stack_.top() =="["){
stack_.pop();
stack_.push("3");
}else{
int sum = 0;
while(stack_.top() != "["){
sum += stoi(stack_.top());
stack_.pop();
}
stack_.pop();
stack_.push(to_string(3*sum));
}
}
}
}
int ans =0;
while(!stack_.empty()){
ans += stoi(stack_.top());
stack_.pop();
}
cout << ans;
return 0;
}