Cod sursa(job #2513226)

Utilizator vali_27Bojici Valentin vali_27 Data 22 decembrie 2019 16:58:44
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>
#define NMAX 200001
using namespace std;

ifstream f ("heapuri.in");
ofstream g ("heapuri.out");

int heap[NMAX],n,m,v[NMAX];

void promovare(int nod)
{
    if(nod > 1)
        if(heap[nod] < heap[nod/2])
        {
            swap(heap[nod],heap[nod/2]);
            promovare(nod/2);
        }

}

int indice_min(int nod)
{
    if(nod*2+1 > n)return nod*2;
    else
        if(heap[nod*2] <= heap[nod*2+1])return nod*2;
        else return nod*2+1;
}

void cernere(int nod)
{
    if(nod <= n/2)
    {
        int im =  indice_min(nod);
        if(heap[nod] > heap[im])
        {
            swap(heap[nod],heap[im]);
            cernere(im);
        }
    }

}

void delete_xth_element(int x)
{
    for(int i = 1;i<=n;++i)
        if(heap[i] == v[x])
    {
        swap(heap[i],heap[n]);
        n--;
        cernere(i);
        break;
    }
}

void citire()
{
    int tip,x,nrop;
    f >> nrop;
    while(nrop--)
    {
        f >> tip;
        // se insereaza
        if(tip == 1)
        {
            f >> x;
            heap[++n] = x;
            v[++m] = x;
            promovare(n);
        }
        else
        // se stege elementul intrat al x lea
        if(tip == 2)
        {
            f >> x;
            delete_xth_element(x);
        }

        else
        // se afiseaza minimul
        g << heap[1] << '\n';
    }
}

int main()
{
    citire();
    return 0;
}