Cod sursa(job #2870452)

Utilizator CristianPavelCristian Pavel CristianPavel Data 12 martie 2022 12:49:45
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#define maxN 200000
using namespace std;

ifstream cin ("heapuri.in");
ofstream cout ("heapuri.out");

int Heap[maxN], N = 0, X, Case, Nr = 0;
int Poz[maxN], Val[maxN];

void Swap (int x, int y)
{
    swap(Heap[x], Heap[y]);
    swap(Poz[Heap[x]], Poz[Heap[y]]);
}

int Peek()
{
    return Val[Heap[1]];
}

int Cmp (int x, int y)
{
    return Val[Heap[x]] < Val[Heap[y]];
}

void DownHeap(int x)
{
    int Son = x * 2;
    if(Son + 1 <= N && Cmp(Son + 1, Son))
        Son +=1;
    if(Son <= N && Cmp(Son, x))
    {
        Swap(Son, x);
        DownHeap(Son);
    }
}

void UpHeap(int x)
{
    int Father = x / 2;
    if(Father && Cmp(x, Father))
    {
        Swap(x, Father);
        UpHeap(Father);
    }
}

void Erase(int x)
{
    Swap(x, N);
    N--;
    DownHeap(x);
    UpHeap(x);
}

void Insert(int x)
{
    N++;
    Nr++;
    Heap[N] = Nr;
    Poz[Nr] = N;
    Val[Nr] = x;
    UpHeap(N);
}

void Afisare(int N)
{
    if(N){
        for(int i = 1; i <= N; i++)
        cout << Val[Heap[i]] << " ";
        cout << endl;
    }
    else cout << "nimic" << "\n";
}

void HeapSort(int N)
{
    while(N)
    {
        Swap(1,N);
        N--;
        DownHeap(1);
    }
}

int main()
{
    cin >> X;
    for(int i = 1; i <= X; i++)
    {
        cin >> Case;
        if(Case == 1){
            int val;
            cin >> val;
            Insert(val);
        }
        else if(Case == 2){
            int Pozitie;
            cin >> Pozitie;
            Erase(Poz[Pozitie]);
        }
        else cout << Peek() << "\n";  
    }
    return 0;

}