Cod sursa(job #3171670)

Utilizator cristianabalcanuCristiana Balcanu cristianabalcanu Data 19 noiembrie 2023 12:38:02
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
#include <bits/stdc++.h>
#define NN 200005
using namespace std;
ifstream fin ("heapuri.in");
ofstream fout ("heapuri.out");

struct Nod
{
    int val, pos;
};

int teste, p[NN], lenh, nrins;
Nod h[NN];

void afish()
{
    for(int i = 1 ; i <= lenh ; i++)
        fout << h[i].val << " ";
    fout << '\n';
}

void push_up(int i)
{
    while(i != 1 && h[i].val < h[i / 2].val)
    {
        swap(p[h[i].pos], p[h[i/2].pos]);
        swap(h[i], h[i/2]);
        i = i / 2;
    }
}

void push_down(int pos)
{
    while ((pos * 2 <= lenh && h[pos*2].val < h[pos].val) ||
            (pos * 2 + 1 <= lenh && h[pos*2+1].val < h[pos].val))
    {
        if (pos * 2 + 1 > lenh || h[pos*2].val < h[pos*2+1].val)
        {
            swap(p[h[pos].pos], p[h[pos*2].pos]);
            swap(h[pos], h[pos*2]);
            pos = pos * 2;
        }
        else
        {
            swap(p[h[pos].pos], p[h[pos*2+1].pos]);
            swap(h[pos], h[pos*2+1]);
            pos = pos * 2 + 1;
        }
    }
}

void push_down_eu(int i)
{
    int j;
    while(i * 2 <= lenh)
    {
        j = i * 2;
        if(j + 1 <= lenh && h[j+1].val < h[j].val)
            j++;
        if(h[j].val >= h[i].val)
            return;
        swap(p[h[i].pos], p[h[j].pos]);
        swap(h[i], h[j]);
        i = j;
    }
}

void insereaza(int x, int pos)
{
    lenh++;
    h[lenh].val = x;
    h[lenh].pos = pos;
    p[pos] =  lenh;
    push_up(lenh);
}

void sterge(int pos)
{
    swap(h[pos], h[lenh]);
    swap(p[h[pos].pos], p[h[lenh].pos]);
    lenh--;
    if(pos > 1 && h[pos/2].val > h[pos].val)
        push_up(pos);
    else
        push_down_eu(pos);
}

int main()
{
    fin >> teste;
    while(teste > 0)
    {
        int t, x;
        fin >> t;
        if(t == 1)
        {
            fin >> x;
            nrins++;
            insereaza(x, nrins);

        }
        else if(t == 2)
        {
            fin >> x;
            sterge(p[x]);
        }
        else
            fout << h[1].val << '\n';
        //afish();
        teste--;
    }
    return 0;
}