Cod sursa(job #2787964)

Utilizator Stefan_DomuncoStefan Domunco Stefan_Domunco Data 24 octombrie 2021 14:54:26
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
//min heap
#include <bits/stdc++.h>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
const int NMAX = 2e5+5;

int position[NMAX], nrel;

struct heap
{
    int val, poz;
}h[NMAX];

int root()
{
    return h[1].val;
}

int father(int poz)
{
    return poz / 2;
}

int left_son(int poz)
{
    return 2 * poz;
}

int right_son(int poz)
{
    return 2 * poz + 1;
}

void percolate(int poz)
{
    while(poz > 1 && h[father(poz)].val > h[poz].val) swap(h[father(poz)], h[poz]), swap(position[h[father(poz)].poz], position[h[poz].poz]), poz = father(poz);
}

void sift(int poz)
{
    int min_son;

    do
    {
        min_son = 0;
        if(left_son(poz) <= nrel)
        {
            min_son = left_son(poz);
            if(right_son(poz) <= nrel && h[right_son(poz)].val < h[min_son].val)
                min_son = right_son(poz);
        }

        if(min_son == 0)
            break ;
        if(h[min_son].val > h[poz].val)
            min_son = 0;
        else swap(h[min_son], h[poz]), swap(position[h[min_son].poz], position[h[poz].poz]), poz = min_son;
    }while(min_son != 0);
}

void add(int val, int poz)
{
    ++nrel;
    h[nrel].val = val;
    h[nrel].poz = poz;
    position[poz] = nrel;

    ///incerc sa urc noul element
    percolate(nrel);
}

void del(int poz)
{
    if(poz == nrel)
    {
        --nrel;
        return ;
    }

    swap(h[poz], h[nrel]);
    swap(position[h[poz].poz], position[h[nrel].poz]);
    --nrel;

    sift(poz);
    percolate(poz);
}
int main()
{
    int n, tip, val, x = 0;

    fin >> n;
    for(int i = 1; i <= n; ++i)
    {
        fin >> tip;
        if(tip == 3)
            fout << root() << '\n';
        else
        {
            fin >> val;
            if(tip == 1)
            {
                ++x;
                add(val, x);
            }
            else del(position[val]);

        }
    }
    return 0;
}