Cod sursa(job #3171663)

Utilizator cristianabalcanuCristiana Balcanu cristianabalcanu Data 19 noiembrie 2023 12:16:01
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.82 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 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
    {
        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;
            }
        }
    }
}

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;
}