Cod sursa(job #2226561)

Utilizator Raoul_16Raoul Bocancea Raoul_16 Data 30 iulie 2018 12:43:27
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <cstdio>
#include <algorithm>
using namespace std;
int k,n,cmd,nh,val[200001],heap[200001],pos[200001];
void hswap(int x,int y)
{
    swap(heap[x],heap[y]);
    swap(pos[heap[x]],pos[heap[y]]);
}
bool cmp(int x,int y)
{
    return val[x]<val[y];
}
void upheap(int x)
{
    int p=(x>>1);
    if (p&&cmp(heap[x],heap[p]))
    {
        hswap(x,p);
        upheap(p);
    }
}
void downheap(int x)
{
    int f=(x<<1);
    f+=(f+1<=nh&&cmp(heap[f+1],heap[f]));
    if (f<=nh&&cmp(heap[f],heap[x]))
    {
        hswap(x,f);
        downheap(f);
    }
}
void ins(int x)
{
    heap[++nh]=x;
    pos[x]=nh;
    upheap(pos[x]);
}
void del(int x)
{
    hswap(x,nh);
    pos[heap[nh]]=0;
    heap[nh--]=0;
    downheap(x);
}
int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
    scanf("%d",&k);
    for(;k;k--)
    {
        scanf("%d",&cmd);
        switch(cmd)
        {
            case 1:
            scanf("%d",&val[++n]);
            ins(n);
            break;
            case 2:
            scanf("%d",&cmd);
            del(pos[cmd]);
            break;
            case 3:
            printf("%d\n",val[heap[1]]);
        }
    }
    return 0;
}