> >
본문 바로가기

Algorithm/BOJ

[BOJ] 2504번 괄호의 값

#include <bits/stdc++.h>
#define FASTIO ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;

string s; 
stack<int> st;

bool check(){
    bool flag = true;
    for (int i = 0; i < s.size(); i++){
        if (s[i] == ')'){
            if (st.empty() || st.top() != '(') {
                flag = false;
                break;
            }
            st.pop();
        }
        else if (s[i] == ']'){
            if (st.empty() || st.top() != '['){
                flag = false;
                break;
            }
            st.pop();
        }
        else st.push(s[i]);
    }
    if (!st.empty()) flag = false;
    if (!flag) return false;
    return true;
}

void solved(int idx){
    if (st.top() == idx) {
        st.pop();
        if (!st.empty() && st.top() > 0){
            int k = st.top();
            st.pop();
            st.push(k - idx);
        }
        else st.push(-idx);
    }
    else{
        int k = st.top();
        st.pop();
        st.pop();
        if (!st.empty() && st.top() > 0){
            int j = st.top();
            st.pop();
            st.push(j + (-idx * k));
        }
        else st.push(-idx * k);
    }    
}

int main(){
    FASTIO;
    
    cin >> s;
    if(!check()) {
        cout << 0;
        return 0;
    }
    
    for (int i = 0; i < s.size(); i++){
        if (s[i] == ')') solved(-2);
        else if (s[i] == ']') solved(-3);          
        else {
            if (s[i] == '(') st.push(-2);
            else st.push(-3);
        }
    }
    
    cout << st.top();
    return 0;
}

 

1. 올바르지 못한 괄호열을 먼저 제거했습니다. 

- 구현에 신경쓰면 함수 한 개로 처리할 수 있을거 같은데 이것저것 조건이 붙을거 같아서 따로 빼냈습니다.

2. 괄호를 닫을 때 숫자를 계산하고, stack의 top이 숫자이면 pop해서 더하고 push합니다.

'Algorithm > BOJ' 카테고리의 다른 글

[BOJ] 14499번 주사위 굴리기  (1) 2024.07.14
[BOJ] 14891번 톱니바퀴  (3) 2024.07.14
[BOJ] 18115번 카드 놓기  (0) 2024.07.10
[BOJ] 31802번 주기 함수 (Easy)  (0) 2024.07.10
[BOJ] 15276번 Palindrmoic Password  (0) 2024.07.10