Cod sursa(job #2835995)

Utilizator Albert_GAlbert G Albert_G Data 19 ianuarie 2022 16:36:37
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>

std::ifstream in("heapuri.in");
std::ofstream out("heapuri.out");

constexpr int N = 2e5+1;
int heap[N], v[N], valPos[N], nh, n;

void swapEl(int pos1, int pos2){
    std::swap(heap[pos1], heap[pos2]);
    valPos[heap[pos1]] = pos1;
    valPos[heap[pos2]] = pos2;
}

void goUp(int pos){
    while(pos > 1 && v[heap[pos]] < v[heap[pos/2]]){
        swapEl(pos, pos/2);
        pos /= 2;
    }
}

void goDown(int pos){
    int rChild = pos * 2, lChild = rChild + 1, parent = pos;
    if(rChild <= nh && v[heap[rChild]] < v[heap[parent]]){
        parent = rChild;
    }
    if(lChild <= nh && v[heap[lChild]] < v[heap[parent]]){
        parent = lChild;
    }
    if(parent != pos){
        swapEl(parent, pos);
        goDown(parent);
    }
}

void add(int val){
    heap[++nh] = val;
    valPos[val] = nh;
    goUp(nh);
}

void remove(int pos){
    if(pos == nh){
        --nh;
        return;
    }
    swapEl(nh, pos);
    --nh;
    goUp(pos);
    goDown(pos);
}

int main(){
    int nrOp;
    in >> nrOp;
    for(int i=0; i<nrOp; ++i){
        int type;
        in >> type;
        switch(type){
            case 1:
                in >> v[++n];
                add(n);
                break;
            case 2:
                int idx;
                in >> idx;
                remove(valPos[idx]);
                break;
            default:
                out << v[heap[1]] << '\n';
        }
    }
}