Cod sursa(job #2952948)

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

namespace FastRead
{
    char __buff[5000];ll __lg = 0 , __p = 0;
    char nc()
    {
        if(__lg == __p){__lg = fread(__buff , 1 , 5000 , stdin);__p = 0;if(!__lg) return EOF;}
        return __buff[__p++];
    }
    template<class T>void read(T&__x)
    {
        T __sgn = 1; char __c;while(!isdigit(__c = nc()))if(__c == '-')__sgn = -1;
        __x = __c - '0';while(isdigit(__c = nc()))__x = __x * 10 + __c - '0';__x *= __sgn;
    }
}

using namespace FastRead;
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;
    read(q);

    int cnt = 0;

    while(q--)
    {
        int t;
        read(t);

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