Cod sursa(job #3293994)

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

int heap[200001], a[200001], posInHeap[200001], n;

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

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) <= n) fiu=left_child(k);
        if(right_child(k) <= n)
            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]);
        }
    }
}

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

void pop(int k) {
    heap[k]=heap[n];
    n--;
    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) {
            a[++n]=x;
            push(x);
        }
        else if(c==2) {
            pop(posInHeap[x]);
        }
        else {
            fout<<a[heap[1]]<<"\n";
        }
    }
    return 0;
}