Cod sursa(job #1981034)

Utilizator tifui.alexandruTifui Ioan Alexandru tifui.alexandru Data 14 mai 2017 16:50:18
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>
#define Nmax (int)2e5+1
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int n,l,v;
int a[Nmax];
int h[Nmax];
int poz[Nmax];
void destory_heap(int x)
{
    while(x/2 and a[h[x]]<a[h[x/2]])
    {
        swap(h[x],h[x/2]);
        poz[h[x]]=x;
        poz[h[x/2]]=x/2;
        x/=2;
    }
}
void lower_heap(int x)
{
    int y=0;
    while(x!=y)
    {
        y=x;
        if(2*y<=l and a[h[2*y]]<a[h[x]])
            x=2*y;
        if(2*y+1<=l and a[h[2*y+1]]<a[h[x]])
            x=2*y+1;
        poz[h[y]]=x;
        poz[h[x]]=y;
        swap(h[x],h[y]);
    }
}
void update_heap(int x)
{
    int i;
    a[++n]=x;
    h[++l]=n;
    poz[n]=l;
    destory_heap(l);
}
void erase_heap(int x)
{
    if(poz[x])
    {
        a[x]=-1;
        destory_heap(poz[x]);
    }
    else return;
    poz[x]=0;
    h[1]=h[l];
    poz[h[l]]=1;
    h[l--]=0;
    lower_heap(1);
}
int main()
{
    int m,op,x,i;
    f>>m;
    for(i=1;i<=m;i++)
    {
        f>>op;
        if(op==3)
            g<<a[h[1]]<<'\n';
        else
        {
            f>>x;
            if(op==1) update_heap(x);
            else erase_heap(x);
        }
    }

    return 0;
}