Cod sursa(job #2809435)

Utilizator TghicaGhica Tudor Tghica Data 26 noiembrie 2021 23:52:05
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.68 kb
#include <fstream>

using namespace std;

int hp[262145], hindex[262145], valindex[200001], lastPoz;

void upHeap(int poz) {
  int aux;
  while (poz != 1 && hp[poz / 2] > hp[poz]) {
    aux = hp[poz / 2];
    hp[poz / 2] = hp[poz];
    hp[poz] = aux;

    aux = hindex[poz / 2];
    hindex[poz / 2] = hindex[poz];
    hindex[poz] = aux;

    aux = valindex[hindex[poz / 2]];
    valindex[hindex[poz / 2]] = valindex[hindex[poz]];
    valindex[hindex[poz]] = aux;

    poz /= 2;
  }
}

void downHeap(int poz) {
  int aux, path = 1;
  while (path && (hp[poz * 2] < hp[poz] or hp[poz * 2 + 1] < hp[poz])) {
    
    path = 0;

    if (poz * 2 <= lastPoz && hp[poz * 2] < hp[poz])///Arata groaznic, dar... atat s-a putut
      path = 1;
    if (poz * 2 + 1 <= lastPoz && hp[poz * 2 + 1] < hp[poz]) {
      path = 2;
      if (poz * 2 <= lastPoz && hp[poz * 2] < hp[poz] && hp[poz * 2] < hp[poz * 2 + 1])
        path = 1;
    }

    if (path == 1) {
      aux = hp[poz * 2];
      hp[poz * 2] = hp[poz];
      hp[poz] = aux;

      aux = hindex[poz * 2];
      hindex[poz * 2] = hindex[poz];
      hindex[poz] = aux;

      aux = valindex[hindex[poz * 2]];
      valindex[hindex[poz * 2]] = valindex[hindex[poz]];
      valindex[hindex[poz]] = aux;

      poz *= 2;
    } else if (path == 2) {
      aux = hp[poz * 2 + 1];
      hp[poz * 2 + 1] = hp[poz];
      hp[poz] = aux;

      aux = hindex[poz * 2 + 1];
      hindex[poz * 2 + 1] = hindex[poz];
      hindex[poz] = aux;

      aux = valindex[hindex[poz * 2 + 1]];
      valindex[hindex[poz * 2 + 1]] = valindex[hindex[poz]];
      valindex[hindex[poz]] = aux;

      poz *= 2;
      poz++;
    }
  }
}

void addHeap(int val, int index) {
  lastPoz++;
  hp[lastPoz] = val;
  hindex[lastPoz] = index;
  valindex[index] = lastPoz;
  upHeap(lastPoz);
}

int topHeap() {
  return hp[1];
}

void elimHeap(int elem) {
  int a, aux;

  a = valindex[elem];

  aux = hp[a];
  hp[a] = hp[lastPoz];
  hp[lastPoz] = aux;

  aux = hindex[a];
  hindex[a] = hindex[lastPoz];
  hindex[lastPoz] = aux;

  aux = valindex[hindex[a]];
  valindex[hindex[a]] = valindex[hindex[lastPoz]];
  valindex[hindex[lastPoz]] = aux;

  hp[valindex[elem]] = 0;
  hindex[valindex[elem]] = 0;
  valindex[elem] = 0;
  lastPoz--;
  downHeap(a);
}

signed main() {
  ifstream cin("heapuri.in");
  ofstream cout("heapuri.out");
  int n, i, a, l = 0;
  cin >> n;
  for (i = 1; i <= n; i++) {
    cin >> a;
    if (a == 1) {
      cin >> a;
      l++;
      addHeap(a, l);
    } else if (a == 2) {
      cin >> a;
      elimHeap(a);
    } else {
      cout << topHeap() << "\n";
    }
  }
  return 0;
}