-
Notifications
You must be signed in to change notification settings - Fork 0
/
1216.cpp
138 lines (122 loc) · 2.17 KB
/
1216.cpp
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <iostream>
using namespace std;
class stack {
private:
char* head;
size_t top;
size_t size;
void doubleSpace();
public:
stack(int defsize = 4096);
~stack();
//stack(const stack& s);
void push(char c);
void pop();
char gettop();
char at(size_t pos);
size_t getsize();
};
char stack::at(size_t pos) {
return head[pos];
}
stack::stack(int defsize) {
size = defsize;
top = 0;
head = new char[size];
}
stack::~stack() {
delete[] head;
}
//stack::stack(const stack& s) {
// size = s.size;
// top = s.top;
// head = new char[size];
// for (int i = 0; i < top; ++i) {
// head[i] = s.head[i];
// }
//}
void stack::push(char c) {
if (top >= size) doubleSpace();
head[top++] = c;
}
void stack::pop() {
if (top == 0) return;
--top;
}
char stack::gettop() {
if (top == 0) return '\0';
return head[top - 1];
}
size_t stack::getsize() {
return top;
}
void stack::doubleSpace() {
size *= 2;
char* tmp = new char[size];
for (int i = 0; i < size / 2; ++i) {
tmp[i] = head[i];
}
delete[] head;
head = tmp;
}
bool checkMatch(stack& s) {
stack t(s.gettop());
char tmp;
for (int i = 0; i < s.getsize(); ++i) {
tmp = s.at(i);
if (tmp == '(' || tmp == '[' || tmp == '{') t.push(tmp);
if (tmp == ')') {
if (t.gettop() == '(') t.pop();
else return false;
}
if (tmp == ']') {
if (t.gettop() == '[') t.pop();
else return false;
}
if (tmp == '}') {
if (t.gettop() == '{') t.pop();
else return false;
}
}
return t.getsize() == 0;
}
int main() {
int n, t;
char tmp;
cin >> n;
stack s;
bool flag = true;
bool last = false;
for (int i = 0; i < n; ++i) {
cin >> t;
switch (t)
{
case 1:
cin >> tmp;
s.push(tmp);
flag = true;
break;
case 2:
s.pop();
flag = true;
break;
case 3:
if (s.getsize()) cout << s.gettop() << endl;
flag = true;
break;
case 4:
if (flag) {
last = checkMatch(s);
cout << (last ? "YES" : "NO") << endl;
flag = false;
}
else {
cout << (last ? "YES" : "NO") << endl;
}
break;
default:
break;
}
}
return 0;
}