Cod sursa(job #2484706)

Utilizator stormy_weatherelena cristina stormy_weather Data 31 octombrie 2019 14:44:23
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.99 kb
#include<iostream>
#include<fstream>
#include<vector>
using namespace std;

int father(int i) {
  return i / 2;
}

int left_son(int i) {
  return 2 * i;
}

int right_son(int i) {
  return 2 * i + 1;
}

void percolate(vector<pair <int, int>> &heap, int k, vector<int> &pos) {
    pair<int, int> val = heap[k];
    while (k > 1 && heap[father(k)].first > val.first) {
      heap[k] = heap[father(k)];
      pos[heap[father(k)].second] = k;
      k = father(k);
    }
    heap[k] = val;
    pos[val.second] = k;
    return;
}

void sift(vector<pair <int, int>> &heap, int k, int n, vector<int> &pos) {
  int son;
  do {
    son = -1;
    if (left_son(k) <= n) {
      son = left_son(k);
      if (right_son(k) <= n && heap[right_son(k)].first < heap[left_son(k)].first)
        son = right_son(k);
      if (heap[k].first > heap[son].first) {
        swap(heap[k], heap[son]);
        swap(pos[heap[k].second], pos[heap[son].second]);
        k = son;
      } else {
        son = -1;
      }
    }
  } while (son > 0);

  return;
}

void delete_element(vector<pair <int, int>> &heap, int init_k, vector<int> &pos) {
  int cur_k = pos[init_k];

  swap(heap[cur_k], heap[heap.size() - 1]);
  swap(pos[heap[cur_k].second], pos[heap[heap.size() - 1].second]);

  heap.pop_back();
  sift(heap, cur_k, heap.size() - 1, pos);
}

int main() {

  #ifdef INFOARENA
  ifstream cin("heapuri.in");
  ofstream cout("heapuri.out");
  #endif

  int n; cin >> n;

  vector<pair <int, int>> a(n);
  for (int i = 0; i < n; i++) {
    cin >> a[i].first;
    if (a[i].first == 1 || a[i].first == 2) {
      cin >> a[i].second;
    }
  }

  vector<int> pos(1, 0);
  vector<pair <int, int>> heap;
  heap.push_back({0, 0});

  for (int i = 0; i < n; i++) {
    if (a[i].first == 1) {
      heap.push_back({a[i].second, pos.size()});
      pos.push_back(pos.size());
      percolate(heap, heap.size() - 1, pos);
    } else if (a[i].first == 2) {
      delete_element(heap, a[i].second, pos);
    } else {
      cout << heap[1].first << "\n";
    }
  }
  return 0;
}