Cod sursa(job #2745205)

Utilizator Ion_ApeliaIon Apelia-Cosmina Ion_Apelia Data 26 aprilie 2021 00:27:21
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <iostream>
#include <fstream>
using namespace std;
#define maxN 200001
ifstream in  ("heapuri.in");
ofstream out ("heapuri.out");

int N=0, nr=0, heap[maxN], list[maxN], poz[maxN];
 
int t(int n) {return n/2;} //tatal
int fs(int n) {return n*2;} //fiul stang
int fd(int n) {return n*2+1;} //fiul drept
int min() {return heap[1];} 

void coboara(int nod)
{
    int f;
    while (true && fs(nod) <= N)
    {
        f = fs(nod);
        if (fd(nod) <= N && heap[f] > heap[fd(nod)])
            f = fd(nod);
        if (heap[f] < heap[nod])
        {
            swap(heap[f], heap[nod]);
            swap(poz[list[f]], poz[list[nod]]);
            swap(list[f], list[nod]);
            nod = f;
        }
        else
            break;
    }
}
 
void urca (int nod)
{
    while (nod != 1 && heap[nod] < heap[t(nod)])
    {
        swap(heap[nod], heap[t(nod)]);
        swap(poz[list[nod]], poz[list[t(nod)]]);
        swap(list[nod], list[t(nod)]);
        nod = t(nod);
    }
}
 
void inserare(int x)
{
    N++;
    nr++;
    heap[N] = x;
    list[N] = nr;
    poz[nr] = N;
    urca(N);
}
 
void stergere(int nod)
{
    heap[nod] = heap[N];
    swap(poz[list[nod]], poz[list[N]]);
    swap(list[nod], list[N--]);
    //N--;
    if (t(nod) && heap[nod] < heap[t(nod)])
        urca(nod);
    else
        coboara(nod);
}
 
int main()
{
    int Nc, operatie, x;
    in>>Nc;
    for (int i=0; i<Nc; i++)
    {
        in>>operatie;
        if (operatie == 1)
        {
            in>>x;
            inserare(x);
        }
        else if (operatie == 2)
        {
            in>>x;
            stergere(poz[x]);
        }
        else
            out<<min()<<endl;
    }
    in.close();
    out.close();
    return 0;
}