Cod sursa(job #2544799)

Utilizator Ioan_AnghelIoan Anghel Ioan_Anghel Data 12 februarie 2020 15:30:55
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>

using namespace std;

ifstream in("heapuri.in");
ofstream out("heapuri.out");

const int N = 200002;
int v[N], h[N], poz[N], nh;

void schimb(int p, int q)
{
    swap(h[p], h[q]);
    poz[h[p]] = p;
    poz[h[q]] = q;
}

void urca(int p)
{
    while(p > 1 && v[h[p]] < v[h[p / 2]]){
        schimb(p, p / 2);
        p /= 2;
    }
}

void adauga(int p)
{
    h[++nh] = p;
    poz[p] = nh;
    urca(nh);
}

void coboara(int p)
{
    int fs = 2 * p, fd = 2 * p + 1, bun = p;
    if(fs <= nh && v[h[fs]] < v[h[bun]]){
        bun = fs;
    }
    if(fd <= nh && v[h[fd]] < v[h[bun]]){
        bun = fs;
    }
    if(bun != p){
        schimb(bun, p);
        coboara(bun);
    }
}

void sterge(int p)
{
    schimb(p, nh--);
    urca(p);
    coboara(p);
}

int main()
{
    int n, nop = 0;
    in >> n;
    for(int i = 1; i <= n; i++){
        int code;
        in >> code;
        if(code == 1){
            in >> v[++nop];
            adauga(nop);
        }
        if(code == 2){
            int x;
            in >> x;
            sterge(poz[x]);
        }
        if(code == 3){
            out << v[h[1]] << "\n";
        }
    }

    return 0;
}