Cod sursa(job #794111)

Utilizator anca1243Popescu Anca anca1243 Data 5 octombrie 2012 17:57:05
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");

int n,h[200001],poz[200001], v[200001];

void schimb(int &a,int &b)
{
    int aux=a;
    a=b;
    b=aux;
}

void coboara(int p)
{
    int fs=2*p,fd=2*p+1,bun=p;
    if(fs<=n && v[h[fs]]<v[h[bun]])   bun=fs;
    if(fd<=n && v[h[fs]]<v[h[bun]])   bun=fd;
    if(bun!=p)
    {
        schimb(h[bun],h[p]);
        poz[h[bun]] = bun;
        poz[h[p]] = p;
        coboara(bun);
    }
}


void urca(int p)
{
    while(p>1 && v[h[p]]<v[h[p/2]])
    {
        schimb(h[p],h[p/2]);
        poz[h[p]] = p;
        poz[h[p/2]] = p/2;
        p/=2;
    }
}

void sterge(int p)
{
    h[p] = h[n--];
    poz[h[p]] = p;
    urca(p);
    coboara(p);
}

int main()
{
    int t,x,k=0,m;
    in>>m;
    for(int i=1;i<=m;i++)
    {
        in>>t;
        if(t==1)
        {
            in>>x;
            v[++k] = x;
            h[++n] = k;
            poz[k] = n;
            urca(n);
        }
        if(t==2)
        {
            in>>x;
            sterge(poz[x]);
        }
        if(t==3)
        {
            out<<v[h[1]]<<'\n';
        }
    }

    return 0;
}