Cod sursa(job #2684949)

Utilizator BogdanRazvanBogdan Razvan BogdanRazvan Data 15 decembrie 2020 12:24:07
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.06 kb
#include <bits/stdc++.h>

using namespace std;

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

void usain_bolt()
{
    ios::sync_with_stdio(false);
    fin.tie(0);
}

const int N = 2e5 + 5;

vector < pair < int, int > > a(N, {0, 0});

int sz = 0, order[N], pos[N];

int dad(int k)
{
    return k / 2;
}

int left_son(int k)
{
    return 2 * k;
}

int right_son(int k)
{
    return 2 * k + 1;
}

void down(int k)
{
    int son;
    do {
        son = 0;
        if(left_son(k) <= sz) {
            son = left_son(k);
            if(right_son(k) <= sz && a[right_son(k)].first < a[left_son(k)].first) {
                son = right_son(k);
            }
            if(a[son].first >= a[k].first) {
                son = 0;
            }
        }
        if(son) {
            swap(pos[a[k].second], pos[a[son].second]);
            swap(a[k], a[son]);
            k = son;
        }
    }
    while(son);
}

void up(int k)
{
    int val = a[k].first;
    int ord = a[k].second;
    while(k > 1 && (val < a[dad(k)].first)) {
        pos[a[k].second] = pos[a[dad(k)].second];
        a[k].first = a[dad(k)].first;
        a[k].second = a[dad(k)].second;
        k = dad(k);
    }
    a[k].first = val;
    a[k].second = ord;
}

void heap_add(int k)
{
    a[++sz] = {k, order[0]};
    pos[order[0]] = sz;
    up(sz);
}

void heap_delete(int k)
{
    a[k] = a[sz];
    --sz;
    if(k > 1 && a[k].first < a[dad(k)].first) {
        up(k);
    }
    else {
        down(k);
    }
}
int main()
{
    usain_bolt();

    int n;
    a[0].first = -1;
    fin >> n;
    for(int i = 1; i <= n; ++i) {
        int type;

        fin >> type;
        if(type == 1) {
            int x;

            fin >> x;
            order[++order[0]] = x;
            heap_add(x);
        }
        else if(type == 2) {
            int x;

            fin >> x;
            heap_delete(pos[order[x]]);
        }
        else {
             fout << a[1].first << "\n";
        }
    }
    return 0;
}