Cod sursa(job #2496210)

Utilizator mihaela.macarie01@yahoo.comMihaela Macarie [email protected] Data 20 noiembrie 2019 14:41:35
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 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;

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)])
    {
        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(h[k],h[son]);
                k=son;
            }
    }while(son);
}

void insert_heap(int nod)
{
    h[++n]=nod;
    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;
            ordine[++j]=nod;
            insert_heap(nod);
        }
        else
        {
            if(o==2)
            {
                x>>nod;
                int pozi;
                for(int p=1;p<=n;p++)
                    if(h[p]==ordine[nod])
                        pozi=p;
                cut(h,n,pozi);
            }
            else
                y<<h[1]<<'\n';
        }
    }
    x.close();
    y.close();
    return 0;
}