Cod sursa(job #1495087)

Utilizator armandpredaPreda Armand armandpreda Data 2 octombrie 2015 16:26:04
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <algorithm>

using namespace std;

ifstream cin("heapuri.in");
ofstream cout("heapuri.out");

const int LIM=200001;
int t, op, x, cat, n, heap[LIM], poz[LIM], timp[LIM];
void schimba(int a, int b);
void baga(int x);
void urca(int nod);
void scoate(int x);
void coboara(int nod);
int main()
{
    cin>>t;
    while(t--)
    {
        cin>>op;
        if(op<3)
        {
            cin>>x;
            if(op==1) baga(x);
            if(op==2) scoate(x);
        }
        else
            cout<<heap[1]<<'\n';
    }
    return 0;
}
void schimba(int a, int b)
{
    swap(heap[a], heap[b]);
    swap(timp[ poz[a] ], timp[ poz[b] ]);
    swap(poz[a], poz[b]);
}
void baga(int x)
{
    heap[++n]=x;
    timp[++cat]=n;
    poz[n]=cat;
    urca(n);
}
void urca(int nod)
{
    while(nod>1 and heap[nod/2]>heap[nod])
    {
        schimba(nod/2, nod);
        nod/=2;
    }
}
void scoate(int x)
{
    int last=timp[x];
    schimba(timp[x], n);
    heap[n]=timp[n]=poz[n]=0;
    n--;
    coboara(last);
}
void coboara(int nod)
{
    int fiu=0;
    if(nod*2<=n)
        fiu=nod*2;
    if(nod*2+1<=n and heap[nod*2]>heap[nod*2+1])
        fiu++;
    if(fiu)
    {
        schimba(nod, fiu);
        coboara(fiu);
    }
}