Cod sursa(job #2409035)

Utilizator CezarTDTodirisca Cezar CezarTD Data 18 aprilie 2019 16:59:23
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

const int N=200010;

int val[N],h[N],pos[N],op,q,x,NR,L,poz;
void heap_swap(int ,int),heap_up(int ),heap_down(int);

int main()
{
    fin>>q;
    for(;q;q--)
    {
        fin>>op;
        if(op==1)
        {
            fin>>val[++NR];
            h[++L]=NR;
            pos[NR]=L;
            heap_up(L);

        }
        if(op==2)
        {
            fin>>x;
            poz=pos[x];
            heap_swap(poz,L);
            L--;
            heap_up(poz);
            heap_down(poz);
        }
        if(op==3)
        {
            fout<<val[h[1]]<<'\n';
        }
    }
    return 0;
}

void heap_swap(int a,int b)
{
    swap(h[a],h[b]);
    pos[h[a]]=a;
    pos[h[b]]=b;
}

void heap_down(int p)
{
    int fiu=2*p;
    if(fiu>L)return;
    if(val[h[fiu]]>val[h[fiu+1]])fiu++;
    if(val[h[p]]>val[h[fiu]])
    {
        heap_swap(p,fiu);
        heap_down(fiu);
    }
}

void heap_up(int p)
{
    int tata=p/2;
    if(!tata)return;
    if(val[h[p]]<val[h[tata]])
    {
        heap_swap(p,tata);
        heap_up(tata);
    }
}