Cod sursa(job #2952944)

Utilizator SochuDarabaneanu Liviu Eugen Sochu Data 10 decembrie 2022 11:23:51
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 kb
#include <bits/stdc++.h>
#define FILES freopen("heapuri.in" , "r" , stdin) , freopen("heapuri.out" , "w" , stdout)

using namespace std;

const int N = 2e5 + 10;

int n , x;
int heap[N] , a[N] , pos[N];

void upg(int node , int x , int ind)
{
    while(node > 1 && a[heap[node / 2]] > x)
    {
        heap[node] = heap[node / 2];
        pos[heap[node]] = node;
        node /= 2;
    }

    heap[node] = ind;
    pos[ind] = node;
}

void rem(int node)
{
    int mn = 0;

    heap[node] = heap[n];
    pos[heap[node]] = node;

    n--;

    do
    {
        mn = 0;

        if(node * 2 <= n)
            mn = node * 2;

        if(node * 2 + 1 <= n)
            if(a[heap[mn]] > a[heap[node * 2 + 1]])
                mn = node * 2 + 1;

        if(mn && a[heap[node]] > a[heap[mn]])
        {
            swap(heap[node] , heap[mn]);
            swap(pos[heap[node]] , pos[heap[mn]]);
        }
        else mn = 0;

        node = mn;
    }while(mn);
}

signed main()
{
    FILES;
    ios_base::sync_with_stdio(0);

    int i;

    int q;
    cin >> q;

    int cnt = 0;

    while(q--)
    {
        int t;
        cin >> t;

        if(t == 1)
        {
            cin >> x;
            a[++cnt] = x;
            ++n;
            upg(n , x , cnt);
        }
        else if(t == 2)
        {
            cin >> x;
            rem(pos[x]);
        }
        else if(t == 3)
        {
            cout << a[heap[1]] << '\n';
        }
    }
    return 0;
}