Cod sursa(job #2298667)

Utilizator Mihai145Oprea Mihai Adrian Mihai145 Data 8 decembrie 2018 12:33:40
Problema Heapuri Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.43 kb
///Min-Heap

#include <fstream>

using namespace std;

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

int N, totalInserts, Heap[200005];
int inserted[200005], pos[200005];

void UpHeap(int index)
{
    int Father = index / 2;

    if(Father && Heap[Father] > Heap[index])
    {
        swap(Heap[Father], Heap[index]);
        swap(pos[Heap[Father]], pos[Heap[index]]);
        UpHeap(Father);
    }
}

void DownHeap(int index)
{
    int Son = index * 2;

    if(Son + 1 <= N && Heap[Son] > Heap[Son + 1])
        Son++;

    if(Son <= N && Heap[Son] < Heap[index])
    {
        swap(Heap[Son], Heap[index]);
        swap(pos[Heap[Son]], pos[Heap[index]]);
        DownHeap(Son);
    }
}

void Insert(int value)
{
    N++;
    totalInserts++;
    Heap[N] = value;
    inserted[totalInserts] = value;
    pos[value] = N;
    UpHeap(N);
}

void Delete(int index)
{
    swap(Heap[index], Heap[N]);
    swap(pos[Heap[index]], pos[Heap[N]]);
    N--;
    DownHeap(index);
}

int main()
{
    int K;
    fin >> K;

    int x, y;
    for(int i = 1; i <= K; i++)
    {
        fin >> x;

        if(x == 1)
            {
                fin >> y;
                Insert(y);
            }
        else if(x == 2)
            {
                fin >> y;
                Delete(pos[inserted[y]]);
            }
        else
            fout << Heap[1] << '\n';
    }

    return 0;
}