Cod sursa(job #2745010)

Utilizator vlad_dimaVlad Dima vlad_dima Data 25 aprilie 2021 18:35:36
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include <bits/stdc++.h>

using namespace std;

#define nmax 200010

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

int n, op, marime_h = 0, elem_v = 0;

int h[nmax], p[nmax], v[nmax];

void muta_sus(int x)
{
    if (x > 1 && v[h[x]] < v[h[x/2]])
    {
        swap(p[h[x]], p[h[x/2]]);
        swap(h[x],h[x/2]);
        muta_sus(x/2);
    }
}

void muta_jos(int x)
{
    if (x <= marime_h / 2)
        {
            int fiu = -1;
            if (x * 2 + 1 <= marime_h)
            {
                if (v[h[x*2+1]] < v[h[x*2]])
                    fiu = x * 2 + 1;
                else
                    fiu = x * 2;
            }
            else if (x * 2 <= marime_h)
                fiu = x * 2;

            if (fiu > 0 && v[h[fiu]] < v[h[x]])
            {
                swap(p[h[x]],p[h[fiu]]);
                swap(h[x],h[fiu]);
                muta_jos(fiu);
            }
        }
}

void insert_h(int x)
{
    elem_v++;
    v[elem_v] = x;
    marime_h++;
    h[marime_h] = elem_v;
    p[elem_v] = marime_h;

    muta_sus(marime_h);

}


void pop_h(int x)
{
    int poz = p[x];
    p[x] = -1;
    p[h[marime_h]] = poz;
    h[poz] = h[marime_h--];
    if (poz > 1 && v[h[poz]] < v[h[poz/2]])
        muta_sus(poz);
    else
        muta_jos(poz);
}
int main()
{


    int x;
    fin>>n;

    for (int i = 0; i < n; i++)
    {
        fin>>op;
        if (op < 3)
            fin>>x;
        switch(op)
        {
            case 1:{
                insert_h(x);
                break;
            }
            case 2:
                {
                    pop_h(x);
                    break;
                }
            case 3:
                {
                    fout<<v[h[1]]<<'\n';
                    break;
                }
        }
    }

}