Cod sursa(job #2389505)

Utilizator Mihnea_BranzeuMihnea Branzeu Mihnea_Branzeu Data 27 martie 2019 10:38:12
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>

using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int h[200002],poz[200002],v[200002],nh;

void swapp(int p,int q)
{
    swap(h[p],h[q]);
    poz[h[p]]=p;
    poz[h[q]]=q;
}

void urca(int p) {
    while(p>1 && v[h[p]]<v[h[p/2]]) {

        swapp(p,p/2);
        p/=2;
    }
}
void adauga(int p)
{
    h[++nh] = p;
    poz[p] = nh;
    urca(nh);
}
void coboara(int p)
{
    int fs=2*p,fd=2*p+1,bun=p;
    if(fs<=nh && v[h[fs]]<v[h[bun]])
        bun=fs;
    if(fd<=nh && v[h[fd]]<v[h[bun]])
        bun=fd;
    if(bun!=p)
    {
        swapp(p,bun);
        coboara(bun);
    }
}
void sterge(int p)
{
    if(p==nh)
    {
        nh--;
        return;
    }
    h[p]=h[nh--];
    poz[h[p]]=p;
    urca(p);
    coboara(p);
}
int main()
{
    int n,operatie,x,citit=0;
    fin>>n;
   for(int i=1;i<=n;i++)
   {
       fin>>operatie;
       switch(operatie)
       {
       case 1:
        fin>>x;
        v[++citit]=x;
        adauga(citit);
        break;
       case 2:
        fin>>x;
        sterge(poz[x]);
        break;
       case 3:
        fout<<v[h[1]]<<"\n";
        break;
       }
   }
    return 0;
}