Computer Science
최소힙 - 배열 구현
IamToday
2020. 2. 4. 16:05
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
|
#include <iostream>
#include <vector>
using namespace std;
int heap[2 * 100000 + 1], heap_idx = 0;
int pop() {
int result = heap[1];
int tmp = heap[1];
heap[1] = heap[heap_idx];
heap[heap_idx] = tmp;
heap_idx--;
int parent = 1;
int child = parent * 2;
if (child + 1 <= heap_idx) {
//가장 마지막 노드
child = heap[child] < heap[child + 1] ? child : child + 1;
}
while (child <= heap_idx && heap[parent] > heap[child]) {
int tmp = heap[parent];
heap[parent] = heap[child];
heap[child] = tmp;
parent = child;
child *= 2;
if (child + 1 <= heap_idx) child = heap[child] < heap[child + 1] ? child : child + 1;
}
return result;
}
void push(int data) {
heap[++heap_idx] = data;
int child = heap_idx;
int parent = heap_idx / 2;
while (child > 1 && heap[parent] > heap[child]) {
int tmp = heap[parent];
heap[parent] = heap[child];
heap[child] = tmp;
child = parent;
parent = child / 2;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int order;
cin >> order;
if (!order) {
// 배열에 값을 넣는다.
if (heap_idx >= 1)
cout << pop() << '\n';
else cout << 0 << '\n';
}
else push(order);
}
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|