Skip to content

Instantly share code, notes, and snippets.

@Baekjoon
Created October 24, 2015 23:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Baekjoon/1ac8d329d982e564a3ea to your computer and use it in GitHub Desktop.
Save Baekjoon/1ac8d329d982e564a3ea to your computer and use it in GitHub Desktop.
11279
#include <cstdio>
#include <algorithm>
using namespace std;
int heap[100001];
int hn;
int pop() {
int ans = heap[1];
heap[1] = heap[hn];
heap[hn--] = 0;
for (int i=1; i*2 <= hn;) {
if (heap[i] > heap[i*2] && heap[i] > heap[i*2+1]) {
break;
} else if (heap[i*2] > heap[i*2+1]) {
swap(heap[i], heap[i*2]);
i = i*2;
} else {
swap(heap[i], heap[i*2+1]);
i = i*2+1;
}
}
return ans;
}
void push(int x) {
heap[++hn] = x;
for (int i=hn; i>1; i/=2) {
if (heap[i/2] < heap[i]) {
swap(heap[i/2],heap[i]);
} else {
break;
}
}
}
int main() {
int t;
scanf("%d",&t);
while (t--) {
int x;
scanf("%d",&x);
if (x == 0) {
if (hn == 0) {
printf("0\n");
} else {
printf("%d\n",pop());
}
} else {
push(x);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment