Cod sursa(job #3211532)

Utilizator camelia22Dragoiu Camelia camelia22 Data 9 martie 2024 14:23:22
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.62 kb
#include <iostream>
#include <fstream>
#define N 200005
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int n, cod, x, h[N], poz[N*1000], a[N], 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 = fiu_stanga(k), dreapta = fiu_dreapta(k);
    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[tata(k)]))
    {
        swap(h[k],h[tata(k)]);
        swap(poz[h[k]],poz[h[tata(k)]]);

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

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

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