Cod sursa(job #1929424)

Utilizator tifui.alexandruTifui Ioan Alexandru tifui.alexandru Data 17 martie 2017 17:03:43
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int a[200005];
int n,l,v,i,t,x,m;
int hp[200010];
int poz[200010];
void raise(int x)
{
    while(x/2 and a[hp[x]]<a[hp[x/2]])
    {
        swap(hp[x],hp[x/2]);
        poz[hp[x]]=x;
        poz[hp[x/2]]=x/2;
        x/=2;
    }
}
void lower(int x)
{
    int y=0;
    while(x!=y)
    {
        y=x;
        if(2*y<=l and a[hp[2*y]]<a[hp[x]])
            x=2*y;
        if(2*y+1<=l and a[hp[2*y+1]]<a[hp[x]])
            x=2*y+1;
        poz[hp[y]]=x;
        poz[hp[x]]=y;
        swap(hp[x],hp[y]);
    }
}
void add(int x)
{
    a[++n]=x;
    hp[++l]=n;
    poz[n]=l;
    raise(l);
}
void rem(int x)
{
    if(poz[x])
    {
        a[x]=-1;
        raise(poz[x]);
    }
    else return;
    poz[x]=0;
    hp[1]=hp[l];
    poz[hp[l]]=1;
    hp[l--]=0;
    lower(1);
}
int main()
{f>>m;
for(i=1;i<=m;i++)
{
    f>>t;
    if(t==3)
        g<<a[hp[1]]<<'\n';
    else
    {
        f>>x;
        if(t==1) add(x);
        else rem(x);
    }
}

    return 0;
}