Cod sursa(job #2545795)

Utilizator georgecristian2002Raducanu George-Cristian georgecristian2002 Data 13 februarie 2020 15:35:32
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include<iostream>
#include<fstream>

using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

const int dim=200005;

int n,v[dim],h[dim],poz[dim],nh,cnt,nr;

void schimb(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]])
    {
    schimb(p,p/2);
    p/=2;
    }
}

void adauga(int x)
{
    h[++nh]=x;
    poz[x]=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)
    {
    schimb(bun,p);
    coboara(bun);
    }
}

void sterge(int p)
{
    schimb(h[nh--],h[p]);
    urca(p);
    coboara(p);
}

int main()
{

    fin>>n;
        for (int i=1,c; i<=n; i++)

    {
        fin >> c;
        if (c == 1)
        {
            fin >> nr;
            v[++cnt] = nr;
            adauga(cnt);
        }
        if (c == 2)
        {
            fin >> nr;
            sterge(nr);
        }
        if (c == 3)
        {
            fout << v[h[1]] << "\n";
        }
    }
    return 0;
}