Cod sursa(job #2153912)

Utilizator dragostanTantaru Dragos Constantin dragostan Data 6 martie 2018 16:06:11
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.41 kb
#include <fstream>
//#include <iostream>
using namespace std;
ifstream in("heapuri.in");
ofstream cout("heapuri.out");
const int DIM = 200001;
int h[DIM], cron[DIM], v[DIM];
int nh, cnt;
void urca(int p);
void coboara(int p);
void adauga(int val);
void sterge(int p);
int main()
{
    int n;
    in >> n;
    for(int i = 1; i <= n; ++i)
    {
        int nc, x;
        in >> nc;
        if(nc != 3)
        {
            if(nc == 1)
            {
                in >> v[++cnt];
                adauga(cnt);
            }
            else if(nc == 2)
            {
                in >> x;
                sterge(cron[x]);
            }
        }
        else
            cout << v[h[1]] << '\n';
    }
    return 0;
}

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

void coboara(int p)
{
    int fs = p * 2, fd = p * 2 + 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)
    {
        swap(h[bun], h[p]);
        cron[h[p]] = p;
        cron[h[bun]] = bun;
        coboara(bun);
    }
}

void adauga(int val)
{
    h[++nh] = val;
    cron[val] = nh;
    urca(nh);
}

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