Cod sursa(job #2506785)

Utilizator eusebiu_alexandruMorar Eusebiu eusebiu_alexandru Data 8 decembrie 2019 19:30:01
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.63 kb
#include<climits>
#include <fstream>
#define nmax 210002
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
long long heap[nmax];
int pozi[nmax],ordine[nmax],teste,cerinta,x, n,i,nr;
void sift(int n, int k)
{
int son=10,pozitie=ordine[k],aux=heap[k];
while(son)
    {
        son=0;
        if(k*2<=n)
        {
            son=k*2;
        }
            if(heap[k*2+1]<heap[k*2] && k*2+1<=n )
                son=k*2+1;
        if(son && aux>heap[son])
        {
            pozi[ordine[son]]=k;
            heap[k]=heap[son];
            ordine[k]=ordine[son];
            k=son;
        }
        else
            son=0;
    }
heap[k]=aux;
ordine[k]=pozitie;
pozi[pozitie]=k;
}
void percolate(int n, int k)
{
    int aux=heap[k],pozitie=ordine[k];
while(k>1 && aux<heap[k/2])
    {
        pozi[ordine[k/2]]=k;
        heap[k]=heap[k/2];
        ordine[k]=ordine[k/2];
        k=k/2;
    }
heap[k]=aux;
ordine[k]=pozitie;
pozi[pozitie]=k;
}
void sterge(int &n ,int k)
{
 heap[pozi[k]]=heap[n];
 pozi[ordine[n]]=pozi[k];
    ordine[pozi[k]]=ordine[n];
    n--;
    percolate(n,pozi[k]);
    sift(n,pozi[k]);
}
void insert(int nod)
{
    heap[++n]=nod;
    nr++;
    pozi[nr]=n;
    ordine[n]=nr;
    percolate(n,n);
}
int main()
{
    f>>teste;
    while(teste)
    {
        teste--;
        f>>cerinta;
        if(cerinta==1)
        {
            f>>x,insert(x);
        }
        else
        {
            if(cerinta==2)
            {
                f>>x,sterge(n,x);
            }
            else
                g<<heap[1]<<'\n';
        }
    }
}