Cod sursa(job #1868894)

Utilizator vazanIonescu Victor Razvan vazan Data 5 februarie 2017 13:46:05
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.68 kb
#include<fstream>
using namespace std;

class PARS_OUT{
private:
    char *buf, tmp[20], len;
    ofstream &fout;
    int buf_size, cursor;
public:
    PARS_OUT(int s, ofstream &f);
    void put_num(int x);
    void put_ch(char c);
    void finish();
};

PARS_OUT::PARS_OUT(int s, ofstream &f):fout(f), buf_size(s), cursor(0){
    buf = new char[buf_size];
}

void PARS_OUT::put_num(int x){
    if(x < 0){
        put_ch('-');
        x *= -1;
    }
    len = 0;
    while(x){
        tmp[len] = x % 10 + '0';
        x /= 10;
        len++;
    }
    for(int i = len - 1; i >= 0; i--)
        put_ch(tmp[i]);
}

void PARS_OUT::put_ch(char c){
    if(cursor == buf_size){
        buf[cursor] = 0;
        fout << buf;
        cursor = 0;
    }
    buf[cursor++] = c;
    return;
}

void PARS_OUT::finish(){
    buf[cursor] = 0;
    fout << buf;
}
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(){
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");
    int n, q, e;
    fin >> n;
    PARS_OUT o(100000, fout);
    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){
            o.put_num(h.top());
            o.put_ch('\n');
        }
    }
    o.finish();
    return 0;
}