Cod sursa(job #2545815)

Utilizator georgecristian2002Raducanu George-Cristian georgecristian2002 Data 13 februarie 2020 15:51:34
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int dim = 200005;

int n,v[dim],h[dim],poz[dim],nh,cnt,nr;

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;
    int fd = 2*p + 1;
    int 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(bun);
    }
}

void sterge(int p)
{
    p = poz[p];
    schimb(p , nh--);
    urca(p);
    coboara(p);
}

int main()
{
    fin >> n;
    for (int i=1,c; i<=n; i++)
    {
        fin >> c;
        if (c == 1)
        {
            fin >> nr;
            v[++cnt] = nr;
            adauga(cnt);
        }
        if (c == 2)
        {
            fin >> nr;
            sterge(nr);
        }
        if (c == 3)
        {
            fout << v[h[1]] << "\n";
        }
    }
    return 0;
}