Cod sursa(job #2744996)

Utilizator IPCristianIlie Cristian IPCristian Data 25 aprilie 2021 18:09:37
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int Heap[200010],A[200010],Pos[200010];
int Nr,L;

void Adaugare(int x)
{

    while ((x/2)&&(A[Heap[x]]<A[Heap[x/2]]))  // II dam shift up lui X
           {
               swap(Heap[x],Heap[x/2]);

               Pos[Heap[x]] = x;
               Pos[Heap[x/2]] = x/2;
               x/=2;
           }
}

void Stergere(int x)
{
    int y = 0;

    while (x != y)
    {
        y = x;

        if ((y*2 <= L)&&(A[Heap[x]]>A[Heap[y*2]])) // y*2 este fiul stang al lui x iar y*2+1 fiul drept
            x = y*2;

        if ((y*2+1 <= L)&&(A[Heap[x]]>A[Heap[y*2+1]])) // La ambele if-uri dorim sa facem ShiftDown lui x
            x = y*2+1;

        swap(Heap[x],Heap[y]);

        Pos[Heap[x]] = x;
        Pos[Heap[y]] = y;


    }
}


int main()
{
    int n,op,x;
    fin>>n;

    for (int i=0; i<n; i++)
    {
        fin>>op;
        if (op == 1)
        {
            fin>>x;

            L++;Nr++;
            A[Nr] = x;
            Heap[L] = Nr;
            Pos[Nr] = L;

            Adaugare(L);

        }
        else if (op == 2)
        {
            fin>>x;

            A[x] = -1;

            Adaugare(Pos[x]);
            Heap[1] = Heap[L];
            L--;
            Pos[Heap[1]] = 1;
            if (L>1)
                Stergere(1);
        }

        else fout<<A[Heap[1]]<<endl;
    }



    fin.close();
    fout.close();
    return 0;
}