Cod sursa(job #2079254)

Utilizator xkz01X.K.Z. xkz01 Data 30 noiembrie 2017 20:49:39
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.32 kb
#include<cstdio>
#include<algorithm>
#define f first
#define s second
using namespace std;
pair<int,int> heap[200002]; ///<element, al catelea a fost inserat>
int lgHeap=0;
bool removed[200002];
void heap_up(int poz){
    while (poz>1) {
        if (heap[poz].f<heap[poz/2].f) {swap(heap[poz], heap[poz/2]); poz/=2;}
            else break;
    }
}
void heap_down(int poz){
    int son;
    while (2*poz<=lgHeap) {
        if (2*poz+1>lgHeap) son=2*poz;
            else {if (heap[2*poz].f<=heap[2*son+1].f) son=2*poz; else son=2*poz+1;}
        if (heap[son].f<heap[poz].f) {swap(heap[son], heap[poz]); poz=son;}
            else return;
    }
}
void cleanup(){
    while (removed[heap[1].s]) {
        swap(heap[1], heap[lgHeap]);
        heap[lgHeap]=make_pair(0,0); lgHeap--;
        heap_down(1);
    }
}
int main(){
    int n, step, i, op, x;
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d", &n);
    step=0;
    for (i=1;i<=n;i++) {
        scanf("%d", &op); if (op<3) scanf("%d", &x);
        switch(op){
            case 1: {heap[++lgHeap]=make_pair(x, ++step); removed[x]=false; heap_up(lgHeap); break;}
            case 2: {removed[x]=true; cleanup(); break;}
            case 3: {printf("%d\n", heap[1].f); break;}
        }
    }
    return 0;
}