1
+ package Heap .P1927 ;
2
+
3
+ import java .io .BufferedReader ;
4
+ import java .io .FileInputStream ;
5
+ import java .io .InputStreamReader ;
6
+ import java .util .ArrayList ;
7
+ import java .util .List ;
8
+
9
+ public class Main {
10
+
11
+ static int N , x ;
12
+ static MinHeap heap ;
13
+
14
+ public static void main (String [] args ) throws Exception {
15
+ // System.setIn(new FileInputStream("src/Heap/P1927/input.txt"));
16
+
17
+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
18
+ N = Integer .parseInt (br .readLine ());
19
+
20
+ heap = new MinHeap ();
21
+ for (int i = 0 ; i < N ; i ++) {
22
+ x = Integer .parseInt (br .readLine ());
23
+ if (x == 0 ) System .out .println (heap .remove ());
24
+ else heap .insert (x );
25
+ // System.out.println(heap.toString());
26
+ }
27
+ }
28
+ }
29
+
30
+ class MinHeap {
31
+ List <Integer > heap ;
32
+
33
+ public MinHeap () {
34
+ this .heap = new ArrayList <>();
35
+ heap .add (0 );
36
+ }
37
+
38
+ public void insert (int value ){
39
+ heap .add (value );
40
+ int current = heap .size () - 1 ;
41
+ int parent = current / 2 ;
42
+
43
+ while (parent != 0 && heap .get (parent ) > heap .get (current )) {
44
+ int temp = heap .get (parent );
45
+ heap .set (parent , heap .get (current ));
46
+ heap .set (current , temp );
47
+
48
+ current = parent ;
49
+ parent = current / 2 ;
50
+ }
51
+ }
52
+
53
+ public int remove (){
54
+ if (heap .size () == 1 )
55
+ return 0 ;
56
+
57
+ int top = heap .get (1 );
58
+ heap .set (1 , heap .get (heap .size () - 1 ));
59
+ heap .remove (heap .size () - 1 );
60
+
61
+ int current = 1 ;
62
+ while (true ) {
63
+ int left = current * 2 ;
64
+ if (left >= heap .size ()){
65
+ break ;
66
+ }
67
+
68
+ int targetIdx = left ;
69
+ int right = current * 2 + 1 ;
70
+ if (right < heap .size () && heap .get (right ) < heap .get (targetIdx )){
71
+ targetIdx = right ;
72
+ }
73
+
74
+ if (heap .get (targetIdx ) < heap .get (current )){
75
+ int temp = heap .get (current );
76
+ heap .set (current , heap .get (targetIdx ));
77
+ heap .set (targetIdx , temp );
78
+ current = targetIdx ;
79
+ } else {
80
+ break ;
81
+ }
82
+ }
83
+
84
+ return top ;
85
+ }
86
+
87
+ @ Override
88
+ public String toString () {
89
+ return "MinHeap{" + heap + "}" ;
90
+ }
91
+ }
0 commit comments