Cod sursa(job #2026140)

Utilizator ARobertAntohi Robert ARobert Data 23 septembrie 2017 19:22:00
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>

using namespace std;

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

int p[200003], nrad, tip, n, total,x,i;
pair<int,int> heap[200003];

void cerne(int k)
{
    int fiu;
    do
    {
        fiu=0;
        if (k*2<=total)
        {
            fiu=k*2;
            if (k*2+1<=n&&heap[k*2+1].first>heap[k*2].first)
                fiu=k*2+1;
            if (heap[fiu].first>=heap[k].first)
            {
                fiu=0;
            }
        }
        if (fiu)
        {
            p[heap[fiu].second]=k;
            p[heap[k].second]=fiu;
            swap(heap[k],heap[fiu]);
        }
    }
    while (fiu);
}

void urca(int k)
{
    while (k>1&&heap[k].first<heap[k/2].first)
    {
        p[heap[k/2].second]=k;
        p[heap[k].second]=k/2;
        swap(heap[k],heap[k/2]);
        k/=2;
    }
}

void ins(int x)
{
    heap[++total].first=x;
    heap[total].second=++nrad;
    p[nrad]=total;
    urca(total);
}

void del(int x)
{
    int poz=p[x];
    swap(heap[poz], heap[total]);
    total--;
    p[x]=0;
    p[heap[total].second]=poz;
    urca(poz);
    cerne(poz);
}

int main()
{
    fin>>n;
    for (i=1;i<=n;i++)
    {
        fin>>tip;
        if (tip==1)
        {
            fin>>x;
            ins(x);
        }
        if (tip==2)
        {
            fin>>x;
            del(x);
        }
        if (tip==3)
        {
            fout<<heap[1].first<<endl;
        }
    }
    return 0;
}