-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1927.cpp
More file actions
64 lines (55 loc) · 1.26 KB
/
1927.cpp
File metadata and controls
64 lines (55 loc) · 1.26 KB
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
// 최소 힙 1927
#include <stdio.h>
int heap[1 << 17];
int last_idx = 0; // index for last element
int temp_idx = 0; // temp index
int Peek(){ // return min element
if(last_idx == 0) return 0;
return heap[1];
}
void Insert(int key){
heap[++last_idx] = key;
temp_idx = last_idx;
while(temp_idx > 1){
if(heap[temp_idx] > heap[temp_idx / 2]) break;
else{ // swap
int temp = heap[temp_idx];
heap[temp_idx] = heap[temp_idx / 2];
heap[temp_idx / 2] = temp;
temp_idx /= 2;
}
}
}
void Delete(){
if(last_idx == 0) return;
heap[1] = heap[last_idx--];
temp_idx = 1;
while(temp_idx <= last_idx / 2){
if(heap[temp_idx] < heap[temp_idx * 2] && heap[temp_idx] < heap[temp_idx * 2 + 1]) break;
if(heap[temp_idx * 2] < heap[temp_idx * 2 + 1]){
int temp = heap[temp_idx];
heap[temp_idx] = heap[temp_idx * 2];
heap[temp_idx * 2] = temp;
temp_idx *= 2;
}
else{
int temp = heap[temp_idx];
heap[temp_idx] = heap[temp_idx * 2 + 1];
heap[temp_idx * 2 + 1] = temp;
temp_idx = temp_idx * 2 + 1;
}
}
}
int main(){
int N;
scanf("%d", &N);
for(int i = 0, t; i < N; i++){
scanf("%d", &t);
if(t > 0) Insert(t);
else{
printf("%d\n", Peek());
Delete();
}
}
return 0;
}