Cod sursa(job #1599907)

Utilizator CrystyAngelDinu Cristian CrystyAngel Data 14 februarie 2016 15:17:42
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("heapuri.in");
ofstream g("heapuri.out");
int h[200100],v[200100],c,poz[200100],n,nn,i,x,m;
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]);
    }
}
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;
    }
}
int main()
{
    f>>m;
    int nr;
    for(i=1;i<=m;i++)
    {
        f>>c;
        switch(c)
        {
        case 1:
            f>>x;
            v[++n]=x;
            h[++nn]=n;
            poz[n]=nn;
            up(nn);
            break;
        case 2:
            f>>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]);
            break;
        case 3:
            g<<v[h[1]]<<'\n';
            break;
        }
    }
}