Post

BOJ2504 괄호의 값 - 미완

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int is_pair(char t, char inp){
    if (t=='[' && inp==']'){
        return 3;
    }
    if (t=='(' && inp==')'){
        return 2;
    }
    return 0;
}

int is_vaild(string t){
    stack<char> s;
    for(auto&e:t){
        if (!s.empty() && is_pair(s.top(),e)){
            s.pop();
        } else {
            s.push(e);
        }
    }
    if (s.empty()){
        return 1;
    }
    return 0;
}

int main() {
	cin.tie(0); cout.tie(0);
	ios::sync_with_stdio(0);
    stack<char> s;
    string t;
    cin >> t;

    // if (is_vaild(t)==0){
    //     cout << 0;
    //     return 0;
    // }

    int res = 0;
    int n=0;
    int d=0;
    for(auto &e:t){
        cout << e <<" n: " << n <<" d: " <<d << " res: "<< res << "\n";
        // push전에 쌍이 만들어지나 본다
        int val=0;
        if (!s.empty())
        val = is_pair(s.top(),e);

        if (val){
        // 쌍이 만들어졌는데 0인 상태라면 2,3 주고
        // 0이 아니라면 2,3을 곱한다
        // 아니라면 push
            if (n==0) n = val;
            else n *= val;

            s.pop();
            d--;
            if(d==0){ // 깊이가 다시 0이된다면... 결과에 더한다
                res += n;
                n=0;
            }
        }
        else {
            s.push(e);
            d++;
        }
    }
    cout << res << "\n";

	return 0;
}

이러면 깊이 0일때 말고는 처리를 못한다…

1
This post is licensed under CC BY 4.0 by the author.