Cod sursa(job #1609486)

Utilizator c0mradec0mrade c0mrade Data 22 februarie 2016 20:34:16
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");

int n,nn,i,m,x,nr,cod,h[200100],v[200100],poz[200100];

void up(int x)
{
    while(x && v[h[x]]<v[h[x/2]])
    {
        swap(h[x],h[x/2]);
        swap(poz[h[x]],poz[h[x/2]]);
        x/=2;
    }
}

void down(int x)
{
    int y;
    while(x!=y)
    {
        y=x;
        if(2*y<=nn && v[h[2*y]]<v[h[x]])x=2*y;
        if(2*y+1<=nn && v[h[2*y+1]]<v[h[x]])x=2*y+1;

        swap(poz[h[x]],poz[h[y]]);
        swap(h[x],h[y]);
    }
}

int main()
{
    in>>m;
    while(m--){
        in>>cod;
        if(cod==1){
            in>>x;
            v[++n]=x;
            h[++nn]=n;
            poz[n]=nn;
            up(nn);
        }
        if(cod==2){
            in>>x;
            nr = h[nn];
            swap(h[poz[x]] , h[nn]);
            swap(poz[h[poz[x]]] , poz[h[nn]]);
            nn--;
            up(poz[nr]);
            down(poz[nr]);
        }
        if(cod==3)
        {
            out<<v[h[1]]<<'\n';
        }
    }
    return 0;
}