본문 바로가기
PS/BOJ

[백준] 2504. 괄호의 값(c++)

by backend 개발자 지망생 2025. 2. 16.

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

 

연속한 값들을 flush 할 때 값 처리에서 애먹었다.

 

다음과 같이 접근을 모두 했을 것이라 생각한다..

별의 별 생각을 다 했었는데,, stk.size()가 같으면 더해주는 방법도 생각해봤다.

그런데 분기 처리가 도저히 안될 것 같았다.

 

결국은 아이디어를 저 위의 그림의 18만 더해주면 좋을텐데....에서 시작하였는데,

(), []가 붙어있는 것들만 더해주면 올바른 괄호열의 값만 더해줄 수 있다.


#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
#include <map>
#include <limits.h>
#include <queue>
#include <set>
#include <math.h>
#include <stack>
#include <deque>

using namespace std;

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    string s;
    stack<char> stk;
    cin >> s;

    int save = 1, answer = 0;

    for (int i = 0; i < s.length(); i++) {
        if (s[i] == '(') {
            save *= 2;
            stk.push(s[i]);
        } else if (s[i] == '[') {
            save *= 3;
            stk.push(s[i]);
        } else if (s[i] == ')') {
            if (stk.empty() || stk.top() != '(') {
                cout << 0;
                return 0;
            }
            if (s[i - 1] == '(') {
                answer += save;
            }
            stk.pop();
            save /= 2;
        } else if (s[i] == ']') {
            if (stk.empty() || stk.top() != '[') {
                cout << 0;
                return 0;
            }
            if (s[i - 1] == '[') {
                answer += save;
            }
            stk.pop();
            save /= 3;
        } else {
            cout << 0;
            return 0;
        }
    }

    if (stk.empty()) {
        cout << answer;
    } else {
        cout << 0;
    }

    return 0;
}

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

[백준] 1926. 그림(c++)  (0) 2025.02.24
[백준] 9012. 괄호(c++)  (0) 2025.02.16
[백준] 10799. 쇠막대기(c++)  (0) 2025.02.12
[백준] 4949. 균형잡힌 세상(c++)  (0) 2025.02.10
[백준] 11003. 최솟값 찾기(c++)  (0) 2025.02.05