Cod sursa(job #2353641)

Utilizator ZappaManIosif Adrian-Mihai ZappaMan Data 24 februarie 2019 14:15:08
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.58 kb
#include <stdio.h>

const int NMAX = 200005;
int N = 0;
int contor = 0;
int L = 0;

int A[NMAX];
int heap[NMAX];
int pos[NMAX];

void swap(int x, int y) {
   int tmp = heap[x];
   heap[x] = heap[y];
   heap[y] = tmp;

   pos[heap[x]] = x;
   pos[heap[y]] = y;
}

void heapify_down(int ix) {
   int l = ix*2;
   int r = ix*2+1;
   while (ix <= L && l <= L) {
      int min_cand = l;
      if (r <= L && A[heap[r]] < A[heap[min_cand]]) {
         min_cand = r;
      }
      if (A[heap[min_cand]] < A[heap[ix]]) {
         swap(min_cand, ix);
         ix = min_cand;
         l = 2*ix;
         r = 2*ix+1;
      } else {
         break;
      }
   }
}

void heapify_up(int ix) {
   int p = ix/2;
   while (p >= 1) {
      if (A[heap[ix]] < A[heap[p]]) {
         swap(ix, p);
         ix = p;
         p = ix / 2;
      } else {
         break;
      }
   }
}

void pop(int ix) {
   int h_ix = pos[ix];
   heap[h_ix] = heap[L];
   pos[heap[L--]] = h_ix;
   pos[ix] = 0;

   if (h_ix > 1 && A[heap[h_ix]] < A[heap[h_ix/2]]) {
      heapify_up(h_ix);
   } else {
      heapify_down(h_ix);
   }
}

int main() {
   freopen("heapuri.in", "r",  stdin);
   freopen("heapuri.out", "w", stdout);

   scanf("%d",&N);
   while (N--) {
      int qt, q;
      scanf("%d", &qt);
      if (qt == 1 || qt == 2) {
         if (qt == 1) {
            scanf("%d", &A[++contor]);
            heap[++L] = contor;
            pos[contor] = L;
            heapify_up(L);
         } else if (qt == 2) {
            scanf("%d", &q);
            pop(q);
         }
      } else {
         printf("%d\n", A[heap[1]]);
      }
   }
   return 0;
}