Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Custom Heam Implementation
- #include <bits/stdc++.h>
- using namespace std;
- class Max_Heap_PQ {
- int Size, N, *heap,parent,child,Min,ind,t,i,j,cur;
- void swap() {
- t = heap[i];
- heap[i] = heap[j];
- heap[j] = t;
- }
- void bubbleUp() {
- while (cur > 1) {
- parent = cur / 2;
- if (heap[parent] > heap[cur]) {
- break;
- }
- i = cur;j = parent;
- swap();
- cur = parent;
- }
- }
- void bubbleDown() {
- while (2 * cur <= N) {
- child = 2 * cur;
- if (child < N && heap[child] < heap[child + 1]) {
- child++;
- }
- if (heap[cur] > heap[child]) {
- break;
- }
- i = cur;j = child;
- swap();
- cur = child;
- }
- }
- public:
- Max_Heap_PQ(int Max) {
- Size = Max;
- N = parent = child = Min = t = ind = 0;
- i = j = cur = 0;
- heap = new int[Size + 1];
- }
- void insert(int key) {
- N++;
- heap[N] = key;
- cur = N;
- bubbleUp();
- }
- int maxKey() {
- return heap[1];
- }
- int getSize(){
- return N;
- }
- void extractMax() {
- i = 1;j = N;
- swap();
- N--;
- cur = 1;
- bubbleDown();
- heap[N + 1] = -1;
- }
- };
- int main() {
- int N, num , i;
- scanf("%d", &N);
- Max_Heap_PQ pq(N);
- for (i = 0; i < N; i++) {
- scanf("%d", &num);
- pq.insert(num);
- }
- while(pq.getSize() != 0){
- printf("%d\n",pq.maxKey());
- pq.extractMax();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment