Cod sursa(job #1868189)

Utilizator vazanIonescu Victor Razvan vazan Data 4 februarie 2017 17:44:38
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include<fstream>
using namespace std;

class HEAP{
private:
    int *Heap, *Poz;
    int *Elem;
    int total;
public:
    HEAP(const int a);
    void push(int x);
    void pop(int x);
    int top();
    void up(int x);
    void down(int x);
};

HEAP::HEAP(const int a):total(0){
    Heap = new int[a];
    Poz = new int[a];
    Elem = new int[a];
};

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

void HEAP::pop(int x){
    int cord = Poz[x];
    Poz[Heap[total]] = cord;
    swap(Heap[total], Heap[cord]);
    total--;
    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 <= total && Elem[Heap[2 * x]] < Elem[Heap[x]])
            next = 2 * x;
        if(2 * x + 1 <= total && 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]];
}
int main(){
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");
    int n, q, e;
    fin >> n;
    HEAP h(200100);
    for(int i(1); i <= n; i++){
        fin >> q;
        if(q == 1){
            fin >> e;
            h.push(e);
        }
        else if(q == 2){
            fin >> e;
            h.pop(e);
        }
        else if(q == 3){
            fout << h.top() << endl;
        }
    }
    return 0;
}