Cod sursa(job #2743565)

Utilizator FunnyStockyMihnea Andreescu FunnyStocky Data 23 aprilie 2021 11:30:45
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.28 kb
#include <cstdio>
#include <iostream>

using namespace std;

const int N = 200000 + 7;
int n;
int ind[N];
int pos[N];
int t[N];

void schimba(int a, int b) {
  swap(t[a], t[b]);
  swap(ind[a], ind[b]);
  pos[ind[a]] = a;
  pos[ind[b]] = b;
}

void urca(int a) {
  if (a == 1) {
    return;
  }
  if (t[a / 2] > t[a]) {
    schimba(a, a / 2);
    urca(a / 2);
  }
}

void coboara(int a) {
  int b = 0;
  if (2 * a <= n) {
    b = 2 * a;
    if (2 * a + 1 <= n && t[2 * a + 1] < t[2 * a]) {
      b = 2 * a + 1;
    }
  }
  if (b > 0 && t[b] < t[a]) {
    schimba(a, b);
    coboara(b);
  }
}

void repara(int a) {
  if (a > 1 && t[a / 2] > t[a]) {
    urca(a);
  } else {
    coboara(a);
  }
}

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

  int q, id = 0;
  scanf("%d", &q);
  while (q--) {
    int type;
    scanf("%d", &type);
    if (type == 1) {
      int x;
      scanf("%d", &x);

      n++;
      id++;
      t[n] = x;
      ind[n] = id;
      pos[id] = n;

      urca(n);
    }
    if (type == 2) {
      int x;
      scanf("%d", &x);
      int b = pos[x];
      schimba(n, b);
      n--;
      repara(b);
    }
    if (type == 3) {
      printf("%d\n", t[1]);
    }
  }

}