Cod sursa(job #2287963)

Utilizator LucianTLucian Trepteanu LucianT Data 22 noiembrie 2018 18:41:19
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
using namespace std;

const int maxN=2e5+1;

int n,sz,tm;

int ord[maxN];
int heap[maxN],where[maxN];

void insertHeap(int x){
    heap[++sz]=x;
    ord[sz]=++tm;
    where[tm]=sz;

    int nod=sz;
    while(nod>1 && heap[nod]<heap[nod/2]){
        swap(heap[nod],heap[nod/2]);
        swap(ord[nod],ord[nod/2]);

        where[ord[nod]]=nod;
        where[ord[nod/2]]=nod/2;
        nod/=2;
    }
}

void popHeap(int nod){
    swap(heap[nod],heap[sz]);
    swap(ord[nod],ord[sz]);
    where[ord[nod]]=nod;
    sz--;

    int son=0;
    while(nod!=son){
        son=nod;

        if(2*son <= sz && heap[nod]>heap[2*son])
            nod=2*son;
        if(2*son+1 <= sz && heap[nod]>heap[2*son+1])
            nod=2*son+1;

        swap(heap[nod],heap[son]);
        swap(ord[nod],ord[son]);

        where[ord[nod]]=nod;
        where[ord[son]]=son;
    }
}

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

    cin>>n;
    for(int i=0;i<n;i++){
        int op;
        cin>>op;

        if(op==1){
            int x;
            cin>>x;
            insertHeap(x);
        } else if(op==2){
            int x;
            cin>>x;
            popHeap(where[x]);
        } else{
            cout<<heap[1]<<'\n';
        }
    }

    return 0;
}