Cod sursa(job #3211747)

Utilizator XIIs12sPeteleu Denis Andrei XIIs12s Data 10 martie 2024 11:33:47
Problema Heapuri Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.4 kb
#include <iostream>
#include <fstream>
#define N 200009
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int n, cod, x, h[N], poz[N], a[N], na, i, k, pozitie, nr;
void jos(int h[], int n, int k)
{
    int fiu = k;
    int stanga = 2*k, dreapta = 2*k+1;
    if (stanga <= n && h[stanga] < h[fiu])
        fiu = stanga;
    if (dreapta <= n && h[dreapta] < h[fiu])
        fiu = dreapta;

    if (fiu != k)
    {
        swap(h[fiu],h[k]);
        swap(poz[h[fiu]],poz[h[k]]);

        jos(h,n,fiu);
    }
}

void sus(int h[], int k)
{
    while ((k >= 1) && (h[k] < h[k/2]))
    {
        swap(h[k],h[k/2]);
        swap(poz[h[k]],poz[h[k/2]]);

        k = k/2;
    }
}
int main()
{
    f >> nr;
    while (nr)
    {
        f >> cod;
        if (cod == 1)
        {
            f >> x;
            h[++n] = x; /// heap
            a[++na] = x; ///vectorul a

            poz[x] = n;///pozitia lui in vector
            sus(h,n);
        }
        else if (cod == 2)
        {
            f >> x;
            k = a[x];///elem x din vector
            pozitie = poz[k];///pozitia lui

            swap(h[pozitie],h[n]);
            swap(poz[h[pozitie]],poz[h[n]]);
            n--; ///sterg

            jos(h,n,pozitie);
            sus(h,pozitie);
        }
        else
            g << h[1] << '\n';
        nr--;
    }
    return 0;
}