Cod sursa(job #2286883)

Utilizator ZappaManIosif Adrian-Mihai ZappaMan Data 20 noiembrie 2018 22:12:58
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.15 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]]];

   //swap(L,ix);
   //pos[heap[L]] = 0;
   int K = pos[ix];
   heap[pos[ix]] = heap[L];
   pos[heap[L]] = pos[ix];
   pos[ix] = 0;

   L--;
   //if (ix > 1 && (A[heap[ix]] < A[heap[ix / 2]])) {
      //heapify_up(ix);
   //} 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) {
      //if (i == 911 || i == 912) {
         //printf("OP NUM: %d\n", i);
         //for (int i = 1; i <= L; ++i) {
            //printf("%d ", A[heap[i]]);
         //}
         //printf("\n");
      //}

      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]]);
         //if (A[heap[1]] == 324) {
            //printf("===========\n");
            //for (int i = 1; i <= L; ++i) {
               //printf("%d ", A[heap[i]]);
            //}
            //printf("\n");
         //}
      }
   }

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