Cod sursa(job #2567805)

Utilizator luci.tosaTosa Lucian luci.tosa Data 3 martie 2020 18:57:57
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include <iostream>
#include <fstream>
#define NMAX 200005
using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

int n,a[NMAX],h[NMAX],heap_size,pos[NMAX],order;
int father(int node) {
    return node/2;
}
int left_son(int node) {
    return 2*node;
}
int right_son(int node) {
    return 2*node+1;
}
void up(int h[],int n,int k) {
    int key=h[k];
    int keypos=k;
    while(k>1 && a[key]<a[h[father(k)]]) {
        swap(pos[keypos],pos[h[father(k)]]);
        h[k]=h[father(k)];
        k=father(k);
    }
    h[k]=key;
}
void down(int h[],int n,int k) {
    int son;
    do {
        son=0;
        if(left_son(k)<=n) {
            son=left_son(k);
            if(right_son(k)<=n && a[h[right_son(k)]]<a[h[left_son(k)]])
                son=right_son(k);
            if(a[h[son]]>=a[h[k]])
                son=0;
            if(son) {
                swap(h[son],h[k]);
                swap(pos[h[son]],pos[h[k]]);
                k=son;
            }
        }
    } while(son);
}
void insert(int h[],int &n,int key) {
    h[n]=key;
    up(h,n,n);
}

void erase(int h[],int &n,int k) {
    h[k]=h[n];
    pos[h[n]]=pos[h[k]];
    n--;
    if(h[k]<h[father(k)])
        up(h,n,k);
    else
        down(h,n,k);
}
int main() {
    fin>>n;
    for(int i=1; i<=n; i++) {
        int p,x;
        fin>>p;
        if(p==1) {
            fin>>x;
            order++;
            heap_size++;
            pos[order]=heap_size;
            a[order]=x;
            insert(h,heap_size,order);
        } else if(p==2) {
            fin>>x;
            erase(h,heap_size,pos[x]);
        } else
            fout<<a[h[1]]<<"\n";
    }
    return 0;
}