Cod sursa(job #2695360)

Utilizator As932Stanciu Andreea As932 Data 12 ianuarie 2021 17:15:54
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.83 kb
#include <fstream>

using namespace std;

ifstream cin("heapuri.in");
ofstream cout("heapuri.out");

typedef long long ll;
const int nmax = 2e5 + 5;

int m, ord, h[nmax], posInH[nmax];
ll num[nmax];

int parent(int node){
    return node / 2;
}

int leftNode(int node){
    return 2 * node;
}

int rightNode(int node){
    return 2 * node + 1;
}

void percolate(int hp[], int node){
    while(node > 0 && num[hp[node]] < num[hp[parent(node)]]){
        posInH[hp[node]] = parent(node);
        posInH[hp[parent(node)]] = node;
        swap(hp[node], hp[parent(node)]);

        node = parent(node);
    }
}

void sift(int hp[], int node){
    int son;

    do {
        son = 0;

        if(leftNode(node) <= m){
            son = leftNode(node);

            if(rightNode(node) <= m && num[hp[rightNode(node)]] < num[hp[leftNode(node)]])
                son = rightNode(node);

            if(num[hp[son]] >= num[hp[node]])
                son = 0;

            if(son){
                swap(hp[son], hp[node]);
                posInH[hp[son]] = son;
                posInH[hp[node]] = node;
                node = son;
            }
        }

    } while(son);
}

void removee(int hp[], int alXlea){
    int node = posInH[alXlea];
    swap(hp[node], hp[m]);
    swap(posInH[hp[node]], posInH[hp[node]]);

    m--;

    if(node > 0 && num[hp[node]] < num[hp[parent(node)]])
        percolate(hp, node);
    else
        sift(hp, node);
}

void operation(){
    int cod;
    ll nr;

    cin >> cod;

    if(cod <= 2)
        cin >> nr;

    if(cod == 1){
        ++m;
        ++ord;

        num[ord] = nr;
        h[m] = ord;
        posInH[ord] = m;

        percolate(h, m);
    } else if(cod == 2){
        removee(h, nr);
    } else
        cout << num[h[1]] << "\n";
}

int main()
{
    int n;
    cin >> n;

    while(n--)
        operation();

    return 0;
}