Cod sursa(job #2999143)

Utilizator rapidu36Victor Manz rapidu36 Data 10 martie 2023 15:39:11
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <fstream>

using namespace std;

const int N = 2e5;

int v[N+1], h[N+1], poz[N+1];

void schimb(int p1, int p2)
{
    swap(h[p1], h[p2]);
    poz[h[p1]] = p1;
    poz[h[p2]] = p2;
}

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

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

void coboara(int h[], int nh, 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 = fd;
    }
    if (bun != p)
    {
        schimb(p, bun);
        coboara(h, nh, bun);
    }
}

void sterge(int h[], int &nh, int p)
{
    if (p == nh)
    {
        nh--;
    }
    else
    {
        schimb(h[p], h[nh--]);
        urca(h, p);
        coboara(h, nh, p);
    }
}

int main()
{
    ifstream in("heapuri.in");
    ofstream out("heapuri.out");
    int nc = 0, nh = 0, nop;
    in >> nop;
    for (int i = 0; i < nop; i++)
    {
        int tip;
        in >> tip;
        if (tip == 1)
        {
            in >> v[++nc];
            adauga(h, nh, nc);
        }
        else if (tip == 2)
        {
            int p;
            in >> p;
            sterge(h, nh, poz[p]);
        }
        else
        {
            out << v[h[1]] << "\n";
        }
    }
    in.close();
    out.close();
    return 0;
}