코딩스토리

Educational Codeforces Round 98 (Rated for Div. 2) - C번 본문

알고리즘/BOJ 문제 풀이

Educational Codeforces Round 98 (Rated for Div. 2) - C번

kimtaehyun98 2020. 12. 27. 21:49

codeforces.com/contest/1452/problem/C

 

Problem - C - Codeforces

 

codeforces.com

기초적인 stack 문제였다.

괄호의 짝을 stack을 사용해서 구하는 문제는 기초중의 기초니까 꼭 알고 넘어가자.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
typedef long long ll;
 
int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int t;
    string str;
    cin >> t;
    while (t--) {
        cin >> str;
        stack<char>s;
        for (int i = 0; i < str.size(); i++) {
            s.push(str[i]);
        }
        int left_s = 0, right_s = 0, left_b = 0, right_b = 0;
        int ans = 0;
        while (!s.empty()) {
            char temp = s.top();
            s.pop();
            if (temp == ')') {
                if (left_s == 0) right_s++;
                else{
                    left_s--;
                    ans++;
                }
            }
            else if (temp == '(') {
                if (right_s > 0) {
                    right_s--;
                    ans++;
                }
            }
            else if (temp == ']') {
                if (left_b == 0) right_b++;
                else {
                    left_b--;
                    ans++;
                }
            }
            else {
                if (right_b > 0) {
                    right_b--;
                    ans++;
                }
            }
        }
        cout << ans << "\n";
    }
}
cs

 

'알고리즘 > BOJ 문제 풀이' 카테고리의 다른 글

백준 1005번 - ACM Craft  (0) 2021.01.01
백준 2056번 - 작업  (0) 2021.01.01
백준 2621번 - 카드게임  (0) 2020.12.27
백준 1197번 - 최소 스패닝 트리  (1) 2020.12.17
백준 15990번 - 1, 2, 3 더하기 5  (0) 2020.11.24
Comments