Cod sursa(job #2496500)

Utilizator mihaela.macarie01@yahoo.comMihaela Macarie [email protected] Data 20 noiembrie 2019 22:24:14
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.8 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,pozi[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];
    while(k>1 && key<h[father(k)])
    {
        swap(pozi[h[father(k)]],pozi[h[k]]);
        swap(h[k],h[father(k)]);
        k=father(k);
    }
    pozi[h[k]]=pozi[key];
    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(pozi[h[k]],pozi[h[son]]);
                swap(h[k],h[son]);
                k=son;
            }
    }while(son);
}

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

void cut(int h[200002],int &n ,int k)
{
    h[k]=h[n];
    pozi[h[k]]=pozi[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,pozi[ordine[nod]]);
            }
            else
                y<<h[1]<<'\n';
        }
    }
    x.close();
    y.close();
    return 0;
}