Cod sursa(job #1868207)

Utilizator vazanIonescu Victor Razvan vazan Data 4 februarie 2017 17:59:49
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.84 kb
#include<cstdio>
#include<algorithm>
using namespace std;

class HEAP{
private:
    int Heap[200100], Poz[200100];
    int Elem[200100];
    int total, heap_len;
public:
    HEAP();
    inline void push(int x);
    inline void pop(int x);
    inline int top();
    inline void up(int x);
    inline void down(int x);
};

HEAP::HEAP():total(0), heap_len(0){
}

void HEAP::push(int x){
    Elem[++total] = x;
    Heap[++heap_len] = total;
    Poz[total] = heap_len;
    up(heap_len);
}

void HEAP::pop(int x){
    int cord = Poz[x];
    Poz[Heap[heap_len]] = cord;
    swap(Heap[heap_len], Heap[cord]);
    heap_len--;
    up(cord);
    down(cord);
}

void HEAP::up(int x){
    while(x > 1 && Elem[Heap[x]] < Elem[Heap[x / 2]]){
        Poz[Heap[x]] = x / 2;
        Poz[Heap[x / 2]] = x;
        swap(Heap[x], Heap[x / 2]);
        x /= 2;
    }
}

void HEAP::down(int x){
    int next;
    do{
        next = 0;
        if(2 * x <= heap_len && Elem[Heap[2 * x]] < Elem[Heap[x]])
            next = 2 * x;
        if(2 * x + 1 <= heap_len && Elem[Heap[2 * x + 1]] < Elem[Heap[2 * x]])
            next = 2 * x + 1;
        if(next){
            Poz[Heap[x]] = next;
            Poz[Heap[next]] = x;
            swap(Heap[x], Heap[next]);
            x = next;
        }
    }while(next);
}

int HEAP::top(){
    return Elem[Heap[1]];
}

HEAP h;
int main(){
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    int n, q, e;
    scanf("%d", &n);
    for(int i(1); i <= n; i++){
        scanf("%d", &q);
        if(q == 1){
            scanf("%d", &e);
            h.push(e);
        }
        else if(q == 2){
            scanf("%d", &e);
            h.pop(e);
        }
        else if(q == 3){
            printf("%d\n", h.top());
        }
    }
    return 0;
}