Cod sursa(job #3211746)

Utilizator XIIs12sPeteleu Denis Andrei XIIs12s Data 10 martie 2024 11:30:16
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.6 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*1000], a[N*100], na, i, k, pozitie, nr;
int tata(int x)
{
    return x / 2;
}
int fiu_stanga(int x)
{
    return 2 * x;
}
int fiu_dreapta(int x)
{
    return 2 * x + 1;
}

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 = tata(k);
    }
}

int minim(int h[])
{
    return h[1];
}

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;
}