Cod sursa(job #2079261)

Utilizator xkz01X.K.Z. xkz01 Data 30 noiembrie 2017 20:54:05
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 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;
int n, step, i, op, x;
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(){
    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);
        if (op==1) {heap[++lgHeap]=make_pair(x, ++step); removed[x]=false; heap_up(lgHeap); continue;}
        if (op==2) {removed[x]=true; cleanup(); continue;}
        if (op==3) {printf("%d\n", heap[1].f); continue;}
    }
    return 0;
}