Cod sursa(job #2498072)

Utilizator mihaela.macarie01@yahoo.comMihaela Macarie [email protected] Data 23 noiembrie 2019 14:19:24
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb

#include <iostream>
#include <fstream>

using namespace std;

ifstream x("heapuri.in");
ofstream y("heapuri.out");

int n,i,nr,ordine[200002],h[200002],j,o,nod,v[200002];

int father(int nod)
{
    return nod/2;
}

int left_son(int nod)
{
    return nod*2;
}

int right_son(int nod)
{
    return nod*2+1;
}

void percolate(int h[200002], int n, int k)
{
    int key=h[k],p=k;
    while(k>1 && key<h[father(k)])
    {
        swap(ordine[k],ordine[father(k)]);
        swap(v[k],v[father(k)]);
        h[k]=h[father(k)];
        k=father(k);
    }
    h[k]=key;

}

void sift(int h[200002],int n, int k)
{
    int son;
    do
    {
        son=0;
        if(left_son(k)<=n)
        {
            son=left_son(k);
            if(right_son(k)<=n && h[right_son(k)]<h[left_son(k)])
                son=right_son(k);
            if(h[son]>=h[k])
                son=0;
        }
        if(son)
        {
            swap(ordine[h[k]],ordine[h[son]]);
            swap(v[h[k]],v[h[son]]);
            swap(h[k],h[son]);
            k=son;
        }
    }while(son);
}

void insert_heap(int nod)
{
    h[++n]=nod;
    ordine[++j]=n;
    v[n]=n;
    percolate(h,n,n);
}

void cut(int h[200002],int &n ,int k)
{
    h[k]=h[n];
    n--;
    if(k>1 && h[k]<h[father(k)])
        percolate(h,n,k);
    else
        sift(h,n,k);
}

int main()
{
    x>>nr;
    for(i=1;i<=nr;i++)
    {
        x>>o;
        if(o==1)
        {
            x>>nod;
            insert_heap(nod);
        }
        else
        {
            if(o==2)
            {
                x>>nod;
                cut(h,n,v[ordine[nod]]);
            }
            else
                y<<h[1]<<'\n';
        }
    }
    x.close();
    y.close();
    return 0;
}