Cod sursa(job #2889780)

Utilizator gizzehhhAsavoaei Bianca Gabriela gizzehhh Data 13 aprilie 2022 11:37:46
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.47 kb
#include <fstream>

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

int dim; /// dimensiunea heap ului
int n, heap[200005], poz[200005], indici[200005];
int j, cod, x, k, i;

void Swap(int a, int b)
{
    swap(heap[a], heap[b]);
    swap(indici[a], indici[b]);
    poz[indici[a]] = a;
    poz[indici[b]] = b;
}


void Up(int x)
{
    if(x == 1)  return;
    if(heap[x/2] > heap[x])
    {
        Swap(x , x/2);
        Up(x/2);
    }
}

void Down(int x)
{
    int k = 0;
    if( 2*x <= dim)
    {
        k = 2*x;
        if( 2*x + 1 <= dim && heap[2*x +1] < heap[2*x])
                k = 2*x + 1;
    }

    if( k > 0 && heap[k] < heap[x])
    {
        Swap(x, k);
        Down(k);
    }
}


void CreateNewHeap(int k)
{
    if(k > 1 && heap[k/2] > heap[k])
         Up(k);
    else
          Down(k);

}


void WriteMinim()
{
    /// mereu radacina este elementul minim
    fout << heap[1] <<"\n";

}


void Insertion()
{
    fin >> x;
    dim++;
    i++;
    heap[dim] = x;
    indici[dim] = i;
    poz[i] = dim;
    Up(dim);
}

void Delete()
{
    fin >> x;
    j = poz[x];
    Swap(dim, j);
    dim --;
    CreateNewHeap(j);
}

int main()
{
    fin >> n;
    for(int p=1; p<=n; p++)
    {
        fin >> cod;
        if(cod == 1)
            Insertion();

        else if(cod == 2)
            Delete();
        else
            WriteMinim();

    }

    return 0;
}