Cod sursa(job #2910715)

Utilizator CristianPavelCristian Pavel CristianPavel Data 24 iunie 2022 17:31:43
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
#include <fstream>
using namespace std;

#define maxN 200000

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

struct Pozitie
{
    int first, second;
};
Pozitie Poz[maxN];

int Heap[maxN], N = 0, Nr;

int Peek()
{
    return Poz[Heap[1]].first;
}

bool Compare(int a, int b)
{
    return Poz[Heap[a]].first < Poz[Heap[b]].first;
}

void Swap(int a, int b)
{
    swap(Heap[a], Heap[b]);
    swap(Poz[Heap[a]].second, Poz[Heap[b]].second);
}

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

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

void Insert(int x)
{
    N ++;
    Heap[N] = N;
    Poz[N].first = x;
    Poz[N].second = N;
    UpHeap(N);
}

void Erase(int x)
{
    int y = Poz[x].second;
    Swap(Poz[x].second, N);
    N--;
    UpHeap(y);
    DownHeap(y);
}

void print()
{
    for(int i = 1; i <= N; ++i)
        cout << Poz[Heap[i]].first << " ";
}

int main()
{
    cin >> Nr;
    for(int i = 1; i <= Nr; ++i)
    {
        int number, value;
        cin >> number;
        if(number == 3) cout << Peek() << endl;
        else{
            cin >> value;
            if(number == 1) Insert(value);
            else Erase(value);
        }
    }
    return 0;
}