Cod sursa(job #1495146)

Utilizator armandpredaPreda Armand armandpreda Data 2 octombrie 2015 17:48:43
Problema Heapuri Scor 100
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, cur, n, lt[LIM];
struct tip
{
    int val, id;
} heap[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].val<<'\n';
    }
    return 0;
}
void schimba(int a, int b)
{
    swap(heap[a], heap[b]);
    lt[ heap[a].id ]=a, lt[ heap[b].id ]=b;
}
void baga(int x)
{
    cur++;
    heap[++n].val=x;
    heap[n].id=cur;
    lt[cur]=n;
    urca(n);
}
void urca(int nod)
{
    while(nod>1 and heap[nod/2].val>heap[nod].val)
    {
        schimba(nod/2, nod);
        nod/=2;
    }
}
void scoate(int x)
{
    int last=lt[x];
    schimba(lt[x], n);
    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].val>heap[nod*2+1].val)
        fiu++;
    if(fiu)
    {
        schimba(nod, fiu);
        coboara(fiu);
    }
}