Cod sursa(job #2293299)

Utilizator IordachescuAncaFMI Iordachescu Anca Mihaela IordachescuAnca Data 30 noiembrie 2018 19:34:02
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include<fstream>
#define NMAX 200006

using namespace std;

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

int val[NMAX], poz[NMAX], heap[NMAX];
int n, i, digit, value, position;
int nh, nr;

int leftson(int i)
{
    return 2*i;
}

int rightson(int i)
{
    return 2*i+1;
}

int parent(int i)
{
    return i/2;
}

void heapup(int i)
{
    int vmin = i;
    int p = parent(i);
    if (p >= 1 && val[heap[p]] > val[heap[vmin]])
    {
        vmin = p;
    }

    if (vmin != i)
    {
        poz[heap[i]] = vmin;
        poz[heap[vmin]] = i;
        swap(heap[i], heap[vmin]);
        heapup(vmin);
    }
}

void heapdown(int i, int m)
{
    int vmax = i;
    int l = leftson(i);
    int r = rightson(i);

    if (l <= m && val[heap[l]] < val[heap[vmax]])
    {
        vmax = l;
    }

    if (r <= m && val[heap[r]] < val[heap[vmax]])
    {
        vmax = r;
    }

    if (vmax != i)
    {
        poz[heap[vmax]] = i;
        poz[heap[i]] = vmax;
        swap(heap[i], heap[vmax]);
        heapdown(vmax, m);
    }
}
void deletex(int i)
{
    heap[i]=heap[nh--];
    poz[heap[i]]=i;
    heapup(i);
    heapdown(i,nh);
}
int main()
{

    fin >> n;

    nr = 0;
    nh = 0;

    for (i = 1; i <= n; i++)
    {
        fin >> digit;

        if (digit == 1)
        {
            fin >> value;

            nr++;
            nh++;
            val[nr] = value;
            poz[nr] = nh;
            heap[nh] = nr;

            heapup(nh);
        }

        if (digit == 2)
        {
            fin >> position;
            deletex(poz[position]);
        }

        if (digit == 3)
        {
            fout << val[heap[1]] << "\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}