Cod sursa(job #2015621)

Utilizator PaulTPaul Tirlisan PaulT Data 26 august 2017 19:31:57
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <fstream>
using namespace std;

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

const int MaxN = 200010;
int n, m, cnt, heap[MaxN], v[MaxN], pos[MaxN], x, t;

void Sift(int k);
void Percolate(int k);
void Insert(int val);
void Delete(int k);

int main()
{
    fin >> m;
    for (int i = 1; i <= m; i++)
    {
        fin >> t;
        if (t == 1)
        {
            fin >> x;
            v[++cnt] = x;
            Insert(cnt);
        }
        else
            if (t == 2)
            {
                fin >> x;
                Delete(pos[x]);
            }
            else
                fout << v[heap[1]] << '\n';
    }


    fin.close();
    fout.close();
}

void Delete(int k)
{
    swap(heap[k], heap[n]);
    n--;
    if (k == n) return;

    if (k > 1 && v[heap[k]] < v[heap[k / 2]])
        Percolate(k);
    else
        Sift(k);
}

void Insert(int val)
{
    heap[++n] = val;
    pos[cnt] = n;
    Percolate(n);
}

void Percolate(int k)
{
    while (k > 1 && v[heap[k]] < v[heap[k / 2]])
    {
        swap(heap[k], heap[k / 2]);
        pos[heap[k]] = k;
        pos[heap[k / 2]] = k / 2;
        k /= 2;
    }
}

void Sift(int k)
{
    int son = 0;
    do
    {
        if (2 * k <= n)
        {
            son = 2 * k;
            if (2 * k + 1 <= n && v[heap[2 * k + 1]] <= v[heap[2 * k]])
                son += 1;
            if (v[heap[son]] >= v[heap[k]])
                son = 0;
        }
        else
            son = 0;
        if (son)
        {
            swap(heap[k], heap[son]);
            pos[heap[k]] = k;
            pos[heap[son]] = son;
            k = son;
        }
    } while (son);
}