Created
December 10, 2019 01:28
-
-
Save jungrae-prestolabs/558b9ead62f8e816c65530cfd09ad70c to your computer and use it in GitHub Desktop.
Java code for heap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.*; | |
class Heap{ | |
int[] A; | |
int N; | |
Heap(int MAXSIZE) { | |
N = 0; | |
A = new int[MAXSIZE + 1]; | |
} | |
void push(int x){ | |
A[++N] = x; | |
for(int i=N; i>1; i/=2){ | |
if(A[i] > A[i/2]){ | |
int temp = A[i]; | |
A[i] = A[i/2]; | |
A[i/2] = temp; | |
} | |
else break; | |
} | |
} | |
void pop(){ | |
A[1] = A[N--]; | |
for(int i=1; i*2<=N; ){ | |
int t = i * 2; | |
if(i*2+1 <= N && A[i*2] < A[i*2+1]) t = i*2 + 1; | |
if(A[i] < A[t]){ | |
int temp = A[i]; | |
A[i] = A[t]; | |
A[t] = temp; | |
i = t; | |
} | |
else break; | |
} | |
} | |
int top(){ | |
return A[1]; | |
} | |
int size(){ | |
return N; | |
} | |
} | |
class solution{ | |
static BufferedReader br; | |
static BufferedWriter bw; | |
static StringTokenizer st; | |
public static void main(String args[]) throws Exception { | |
br = new BufferedReader(new InputStreamReader(System.in)); | |
bw = new BufferedWriter(new OutputStreamWriter(System.out)); | |
int T = Integer.parseInt(br.readLine()); | |
for(int Test=1; Test<=T; Test++){ | |
int N = Integer.parseInt(br.readLine()); | |
Heap heap = new Heap(N); | |
bw.write("#" + Test); | |
for(int i=1; i<=N; i++){ | |
st = new StringTokenizer(br.readLine()); | |
int type = Integer.parseInt(st.nextToken()); | |
if(type == 1){ | |
int x = Integer.parseInt(st.nextToken()); | |
heap.push(x); | |
} | |
else { | |
if(heap.size() > 0){ | |
bw.write(" " + heap.top()); | |
heap.pop(); | |
} | |
else bw.write(" -1"); | |
} | |
} | |
bw.write("\n"); | |
} | |
bw.flush(); | |
bw.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment