Cod sursa(job #2286911)

Utilizator ZappaManIosif Adrian-Mihai ZappaMan Data 20 noiembrie 2018 23:29:26
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.68 kb
#include <stdio.h>

const int NMAX = 200005;

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

int N;
int L = 0;
int contor = 1;



void swap(int x, int y) {
   int aux;

   aux = heap[x];
   heap[x] = heap[y];
   heap[y] = aux;

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

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

void heapify_down(int ix) {
   int p = ix;

   int l = 2 * p;
   int r = 2 * p + 1;

   while (l <= L) {
      int min_c = l;
      if (r <= L && A[heap[r]] < A[heap[l]]) {
         min_c = r;
      }

      if (A[heap[min_c]] < A[heap[p]]) {
         swap(min_c, p);
         p = min_c;
         l = 2 * p;
         r = 2 * p + 1;
      } else {
         break;
      }
   }
}

int pop(int ix) {
   int val = A[heap[pos[ix]]];

   int K = pos[ix];
   heap[pos[ix]] = heap[L];
   pos[heap[L]] = pos[ix];
   pos[ix] = 0;

   L--;
   if (ix > 1 && (A[heap[K]] < A[heap[K / 2]])) {
      heapify_up(K);
   } else {
      heapify_down(K);
   }

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

   scanf("%d", &N);

   for (int i = 1; i <= N; ++i) {
      int t;
      scanf("%d", &t);
      if (t == 1) {
         int val;
         scanf("%d", &val);

         L += 1;
         A[contor] = val;
         heap[L] = contor;
         pos[contor++] = L;

         heapify_up(L);
      } else if (t == 2) {
         int ix;
         scanf("%d", &ix);
         pop(ix);
      } else {
         printf("%d\n", A[heap[1]]);
      }
   }

   fclose(stdin);
   fclose(stdout);
   return 0;
}