Cod sursa(job #2491389)

Utilizator popashtefan10Popa Stefan popashtefan10 Data 12 noiembrie 2019 15:22:32
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <iostream>
#include <cstdio>
#define NMAX 200000

using namespace std;

int n, h_size, ord;
int heap[NMAX + 5], f[NMAX + 5], val[NMAX + 5];

void urcare(int poz) {
  if(poz > 1) {
    if(val[heap[poz / 2]] > val[heap[poz]]) {
      swap(heap[poz], heap[poz / 2]);
      urcare(poz / 2);
    }
  }
}

void insert_heap(int x) {
  heap[++h_size] = x;
  urcare(h_size);
}

void coborare(int poz) {
  if(2 * poz + 1 <= h_size) { /// 2 fii
    int pozmin;

    if(val[heap[2 * poz]] < val[heap[2 * poz + 1]])
      pozmin = 2 * poz;
    else
      pozmin = 2 * poz + 1;
    if(val[heap[poz]] > val[heap[pozmin]]) {
      swap(heap[poz], heap[pozmin]);
      coborare(pozmin);
    }
  }
  else if(2 * poz == h_size) /// 1 fiu
    if(val[heap[poz]] > val[heap[2 * poz]]) {
      swap(heap[poz], heap[2 * poz]);
      coborare(2 * poz);
    }
}

void delete_heap(int poz) {
  swap(heap[poz], heap[h_size]);
  h_size--;
  coborare(poz);
}

int top() {
  while(f[heap[1]])
    delete_heap(1);
  return val[heap[1]];
}

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

  scanf("%d", &n);
  for(int i = 1; i <= n; i++) {
    scanf("%d", &tip);
    if(tip != 3)
      scanf("%d", &x);
    if(tip == 1) {
      val[++ord] = x;
      insert_heap(ord);
    }
    else if(tip == 2)
      f[x] = 1;
    else
      printf("%d\n", top());
  }

  return 0;
}