Cod sursa(job #3293998)

Utilizator bazgKleinknecht Dorin bazg Data 14 aprilie 2025 20:59:18
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
#include<bits/stdc++.h>
using namespace std;
int heap[200001], a[200001], posInHeap[200001], nA, nH;

#define father(k) k/2
#define left_child(k) k*2
#define right_child(k) k*2+1

void printHeap() {
    for(int i=1; i<=nH; i++) {
        cout<<a[heap[i]]<<" ";
        if(log2(i+1) == floor(log2(i+1))) cout<<"\n";
    }
}

void urc(int k) {
    while(k>1 && a[heap[father(k)]]>a[heap[k]]) {
        posInHeap[heap[k]]=father(k);
        posInHeap[heap[father(k)]]=k;
        swap(heap[k], heap[father(k)]);
        k=father(k);
    }
}

void cobor(int k) {
    int fiu=-1;
    while(fiu) {
        fiu=0;
        if(left_child(k) <= nH){
            fiu=left_child(k);
            if(right_child(k) <= nH && a[heap[right_child(k)]]<a[heap[fiu]]) fiu=right_child(k);
            if(a[heap[fiu]]>=a[heap[k]]) fiu=0;
        }
        if(fiu) {
            posInHeap[heap[fiu]] = k;
            posInHeap[heap[k]] = fiu;
            swap(heap[k], heap[fiu]);
            k=fiu;
        }
    }
}

void push(int x) {
    posInHeap[nA]=nH;
    heap[nH]=nA;
    urc(nH);
}

void pop(int k) {
    heap[k]=heap[nH];
    posInHeap[heap[k]]=k;
    nH--;
    if(k>1 && a[heap[k]]<a[heap[father(k)]]) urc(k);
    else cobor(k);
}

int main(){
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    int q; cin>>q;
    while(q--) {
        int c, x; cin>>c;
        if(c<3) cin>>x;
        if(c==1) {
            a[++nA]=x;
            nH++;
            push(x);
        }
        else if(c==2) {
            pop(posInHeap[x]);
        }
        else {
            cout<<a[heap[1]]<<"\n";
        }
    }
    return 0;
}