Cod sursa(job #3211537)

Utilizator camelia22Dragoiu Camelia camelia22 Data 9 martie 2024 14:35:28
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 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;

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)
{
    int tata = k / 2;
    while ((k >= 1) && (h[k] < h[tata]))
    {
        swap(h[k],h[tata]);
        swap(poz[h[k]],poz[h[tata]]);

        k = tata;
    }
}

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