Cod sursa(job #2016449)

Utilizator LucaSeriSeritan Luca LucaSeri Data 29 august 2017 14:11:10
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.73 kb
#include <bits/stdc++.h>

using namespace std;

const int MaxN = 2e5 + 10;

int n;
int s = 0, nr = 0;

int v[MaxN], Heap[MaxN], poz[MaxN];

void percolate(int x){
    while(x / 2 && v[Heap[x]] < v[Heap[x/2]]){
        swap(Heap[x], Heap[x/2]);

        poz[Heap[x]] = x;
        poz[Heap[x/2]] = x/2;

        x /= 2;
    }
}

void sift(int x){
    int son;
    do{
        son = 0;
        if(x<<1 <= s){
            son = x<<1;
            if((x<<1|1) <= s && v[Heap[x<<1]] > v[Heap[x<<1|1]]){
                son = x<<1|1;
            }
            if(v[Heap[son]] >= v[Heap[x]]){
                son = 0;
            }
        }
        if(son){
            swap(Heap[x], Heap[son]);
            poz[Heap[x]] = x;
            poz[Heap[son]] = son;
            x = son;
        }

    } while(son);

}
int main(){
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    scanf("%d", &n);

    for(int i = 0; i < n; ++i){
        int cd;
        scanf("%d", &cd);
        int x;
        if(cd < 3){
            scanf("%d", &x);
        }

        if(cd == 1){
            ++s, ++nr;
            v[nr] = x;
            Heap[s] = nr;
            poz[nr] = s;
            percolate(s);
            poz[Heap[1]] = 1;
        }

        if(cd == 2){
            v[x] = -1;
            swap(Heap[poz[x]], Heap[s]);
            poz[Heap[poz[x]]] = poz[x];
            Heap[s] = 0;
            --s;
            if(poz[x] <= s){
                if(poz[x] > 1 && Heap[poz[x]] < Heap[poz[x]/2]) percolate(poz[x]);
                else sift(poz[x]);
            }
        }

        if(cd == 3){
            printf("%d\n", v[Heap[1]]);
        }
    }
    return 0;
}