Cod sursa(job #2744930)

Utilizator vlad_dimaVlad Dima vlad_dima Data 25 aprilie 2021 15:54:00
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <bits/stdc++.h>

using namespace std;


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

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

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

void heap_push(int x)
{
    v[++elem_v] = x;

    h[++marime_h] = elem_v;     ///adaugam nr intrarii elem in heap

    p[elem_v] = marime_h;       ///la ce pozitie in heap se afla

    x = marime_h;

    while (x / 2 && v[h[x]] < v[h[x/2]])
    {
        swap(p[h[x]], p[h[x/2]]);
        swap(h[x],h[x/2]);
        x /= 2;
    }
}


void heap_pop(int x)
{
    v[x] = 0;

    swap(h[p[x]], h[marime_h--]);

    int aux = p[x];
    p[x] = -1;
    x = aux;   ///aducem elementul in pozitia corecta
    p[h[x]] = x;

    while (x / 2 && v[h[x]] < v[h[x/2]])
    {
        swap(p[h[x]], p[h[x/2]]);
        swap(h[x],h[x/2]);
        x /= 2;
    }

    while (x * 2 <= marime_h)
    {
        int ok = 0;
        if (v[h[x]] > v[h[x*2]])
        {
            swap(p[h[x]], p[h[x*2]]);
            swap(h[x],h[x*2]);
            ok = 1;
        }
         if (v[h[x]] > v[h[x*2+1]] && x * 2 + 1 <= marime_h)
        {
            swap(p[h[x]], p[h[x*2+1]]);
            swap(h[x],h[x*2+1]);
            ok = 1;
        }
        x *= 2;
        if (ok == 0)
            break;

    }
}

int main()
{


    int x;
    fin>>n;

    for (int i = 0; i < n; i++)
    {
        fin>>op;
        switch(op)
        {
            case 1:{fin>>x; heap_push(x);break;}
            case 2:{fin>>x; heap_pop(x);break;}
            case 3:{fout<<v[h[1]]<<endl; break;}
        }
    }

}