Mai intai trebuie sa te autentifici.

Cod sursa(job #3293996)

Utilizator bazgKleinknecht Dorin bazg Data 14 aprilie 2025 20:31:30
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include<bits/stdc++.h>
using namespace std;
ifstream fin("heapuri.in"); ofstream fout("heapuri.out");

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) {
    //if(a[k]==-9) cout<<"YOOO\n";
    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)
            if(a[heap[right_child(k)]] < a[heap[fiu]]) fiu=right_child(k);

        if(!fiu || a[heap[fiu]]>a[heap[k]]) fiu=0;
        else {
            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];
    nH--;
    if(k>1 && a[heap[k]]<a[heap[father(k)]]) urc(k);
    else cobor(k);
}

int main(){
    int q; fin>>q;
    while(q--) {
        int c, x; fin>>c;
        if(c<3) fin>>x;
        if(c==1) {
           // cout<<"__"<<1<<" "<<x<<"\n";
            a[++nA]=x;
            nH++;
            push(x);
        }
        else if(c==2) {
            //cout<<"__"<<2<<" "<<x<<"\n";
            pop(posInHeap[x]);
        }
        else {
            fout<<a[heap[1]]<<"\n";
        }
    }
    return 0;
}