본문 바로가기
PS/BOJ

[백준] 10799. 쇠막대기(c++)

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

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

 

쇠막대기 자르는 문제였다. () 일 때 조건 처리가 중요했다.


#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);

    int n, ans = 0;

    string s;
    stack<char> stk;

    cin >> s;

    for (int i = 0; i < s.size(); i++) {
        if (s[i] == '(') {
            stk.push(s[i]);
            ans += 1;
        }
        else if (s[i] == ')' && !stk.empty()) {
            if (i >= 1 && s[i-1] == '(') {
                stk.pop();
                ans += stk.size() - 1; // 1은 레이저로 쓴 (
            }
            else {
                stk.pop();
            }
        }
    }

    cout << ans;

    return 0;
}

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

[백준] 9012. 괄호(c++)  (0) 2025.02.16
[백준] 2504. 괄호의 값(c++)  (0) 2025.02.16
[백준] 4949. 균형잡힌 세상(c++)  (0) 2025.02.10
[백준] 11003. 최솟값 찾기(c++)  (0) 2025.02.05
[백준] 5430. AC(c++)  (0) 2025.02.05