Cod sursa(job #2882964)

Utilizator acostin643costin andrei acostin643 Data 31 martie 2022 23:38:40
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <fstream>

using namespace std;

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

const int NMAX = 200000;

int h[4 * NMAX + 5], poz[NMAX + 5], intro[NMAX + 5];

int n, k, p;

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

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

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

void mySwap(int a, int b)
{
    swap(poz[intro[a]], poz[intro[b]]);
    swap(intro[a], intro[b]);
}


void sift(int p)
{
    while(left_son(p) <= k)
    {
        int dest = left_son(p);
        if(right_son(p) <= k && h[intro[left_son(p)]] > h[intro[right_son(p)]])
            dest = right_son(p);
        if(h[intro[p]] > h[intro[dest]])
            mySwap(p, dest);
        else
            break;
        p = dest;
    }
}

void percolate(int p)
{
    while(p > 1 && h[intro[p]] < h[intro[father(p)]])
    {
        mySwap(p, father(p));
        p = father(p);
    }
}

void insrt(int val)
{
    n++;
    h[n] = val;
    k++;
    intro[k] = n;

    poz[n] = k;

    percolate(k);
}

void cut(int key)
{
    p = poz[key];
    mySwap(p, k);
    k--;
    percolate(p);
    sift(p);
}

int main()
{
    int m, type, val;
    fin >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> type;
        if(type == 1)
        {
            fin >> val;
            insrt(val);
        }

        if(type == 2)
        {
            fin >> val;
            cut(val);
        }

        if(type == 3)
            fout << h[intro[1]] << '\n';
    }

    fin.close();
    fout.close();
    return 0;
}