[BaekJoon] 28278번 - 스택 2 [Java][C++]
[BaekJoon] 28278번 - 스택 2 [Java][C++]
1. 아이디어
BaekJoon 10828번 - 스택 문제에서 제한만 커진 문제로 동일한 로직으로 해결할 수 있다.
2. 코드
1. 풀이 [Java]
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
import java.io.*;
import java.util.*;
public class Main {
static final int MX = 1000000;
static int[] stack = new int[MX];
static int pos = 0;
static void push(int x) {
stack[pos++] = x;
}
static int pop() {
return stack[--pos];
}
static int size() {
return pos;
}
static boolean empty() {
return pos == 0;
}
static int top() {
return stack[pos - 1];
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
while (n-- > 0) {
st = new StringTokenizer(br.readLine());
int c = Integer.parseInt(st.nextToken());
if (c == 1) {
int x = Integer.parseInt(st.nextToken());
push(x);
} else if (c == 2) {
if (empty()) {
sb.append("-1\n");
} else {
sb.append(pop()).append("\n");
}
} else if (c == 3) {
sb.append(size()).append("\n");
} else if (c == 4) {
if (empty()) {
sb.append("1\n");
} else {
sb.append("0\n");
}
} else {
if (empty()) {
sb.append("-1\n");
} else {
sb.append(top()).append("\n");
}
}
}
System.out.println(sb);
}
}
2. 풀이 [C++]
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
#include <bits/stdc++.h>
using namespace std;
const int MX = 1000000;
int st[MX];
int pos = 0;
void push(int x) {
st[pos++] = x;
}
void pop() {
pos--;
}
int size() {
return pos;
}
bool empty() {
return pos == 0;
}
int top() {
return st[pos - 1];
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
while (n--) {
int c;
cin >> c;
if (c == 1) {
int x;
cin >> x;
push(x);
} else if (c == 2) {
if (empty()) {
cout << -1 << '\n';
} else {
cout << top() << '\n';
pop();
}
} else if (c == 3) {
cout << size() << '\n';
} else if (c == 4) {
cout << empty() << '\n';
} else {
if (empty()) {
cout << -1 << '\n';
} else {
cout << top() << '\n';
}
}
}
}
3. 디버깅
없음.
4. 참고
없음.
This post is licensed under CC BY 4.0 by the author.