[BaekJoon] 18258번 - 큐 2 [Java][C++]
[BaekJoon] 18258번 - 큐 2 [Java][C++]
1. 아이디어
BaekJoon 10845번 - 큐 문제에서 제한만 커진 문제로 동일한 로직으로 해결할 수 있다.
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
69
70
71
72
73
74
75
76
77
78
import java.io.*;
import java.util.*;
public class Main {
static final int MX = 2000000;
static int[] queue = new int[MX];
static int front = 0, rear = 0;
static void push(int x) {
queue[rear++] = x;
}
static int pop() {
return queue[front++];
}
static int size() {
return rear - front;
}
static boolean empty() {
return front == rear;
}
static int front() {
return queue[front];
}
static int back() {
return queue[rear - 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());
String c = st.nextToken();
if (c.equals("push")) {
int x = Integer.parseInt(st.nextToken());
push(x);
} else if (c.equals("pop")) {
if (empty()) {
sb.append("-1\n");
} else {
sb.append(pop()).append("\n");
}
} else if (c.equals("size")) {
sb.append(size()).append("\n");
} else if (c.equals("empty")) {
if (empty()) {
sb.append("1\n");
} else {
sb.append("0\n");
}
} else if (c.equals("front")) {
if (empty()) {
sb.append("-1\n");
} else {
sb.append(front()).append("\n");
}
} else {
if (empty()) {
sb.append("-1\n");
} else {
sb.append(back()).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
63
64
65
66
67
68
69
70
71
72
#include <bits/stdc++.h>
using namespace std;
const int MX = 2000000;
int q[MX];
int s = 0, e = 0;
void push(int x) {
q[e++] = x;
}
void pop() {
s++;
}
int size() {
return e - s;
}
bool empty() {
return s == e;
}
int front() {
return q[s];
}
int back() {
return q[e - 1];
}
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
while (n--) {
string c;
cin >> c;
if (c == "push") {
int x;
cin >> x;
push(x);
} else if (c == "pop") {
if (empty()) {
cout << -1 << '\n';
} else {
cout << front() << '\n';
pop();
}
} else if (c == "size") {
cout << size() << '\n';
} else if (c == "empty") {
cout << empty() << '\n';
} else if (c == "front") {
if (empty()) {
cout << -1 << '\n';
} else {
cout << front() << '\n';
}
} else {
if (empty()) {
cout << -1 << '\n';
} else {
cout << back() << '\n';
}
}
}
}
3. 디버깅
없음.
4. 참고
없음.
This post is licensed under CC BY 4.0 by the author.