Cod sursa(job #2624642)

Utilizator dariahazaparuHazaparu Daria dariahazaparu Data 5 iunie 2020 01:58:48
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

int n, heap[1000000005], crono[1000000005], pos[1000000005], size, nr;
///crono - numerele adaugate in heap in ordine cronologica
///heap[i] - indicele in crono[] a unui numar, practic heap cu indici
///pos[i] - pozitia in care se afla un numar in heap dupa indice

void Push(int val){
    crono[++nr] = val;
    heap[++size] = nr;
    pos[nr] = size;
    val = pos[nr];

    while(val / 2 and (crono[heap[val]] < crono[heap[val / 2]] or heap[val / 2] == -1)){
        if(heap[val / 2] == -1){
            pos[heap[val]] = val / 2;
            swap(heap[val],heap[val / 2]);
            val /= 2;
        } else {
            swap(pos[heap[val]], pos[heap[val / 2]]);
            swap(heap[val], heap[val / 2]);
        }
        val /= 2;
    }
}

void Pop(int pozitie){
    int poz = pos[pozitie];
    int y;
    while(heap[poz * 2] > 0 or heap[poz * 2 + 1] > 0){
        if(heap[poz * 2] > 0)
            y = poz * 2;
        if(heap[poz * 2 + 1] > 0 and crono[heap[poz * 2 + 1]] < crono[heap[poz * 2]])
            y = poz * 2 + 1;
        else if(heap[poz * 2]<=0){
            y = poz * 2 + 1;
        }
        swap(pos[heap[poz]],pos[heap[y]]);
        swap(heap[poz],heap[y]);
        poz = y;
    }
    heap[pos[pozitie]] = -1;
}

int main(){
    int op, x;
    fin >> n;
    for (int i = 0; i < n; ++i) {
        fin >> op;

        if(op < 3)
            fin >> x;

        if (op == 1) Push(x);
        else if (op == 2) Pop(x);
        else if (op == 3) fout << crono[heap[1]] << '\n';
    }
    return 0;
}