Cod sursa(job #2733422)

Utilizator mentolnothingmoreNegrut Maria Daniela mentolnothingmore Data 30 martie 2021 13:56:00
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream>
#include <bits/stdc++.h>
#include <cstring>
#include <stack>
#include <vector>
#include <unordered_map>

using namespace std;

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

/*
Heap cu pozitii
-> trb vector sa stiu elementele
-> trb sa am un vector unde tin pozitile din heap pt stergere ??
*/

int N, op, x, L = 0, nr = 0;
int H[200010], P[200010];

void urca(int poz)
{
    if (poz > 0)
    {
        int tata = (poz - 1)/2;
        if (P[H[tata]] > P[H[poz]])
        {
            swap(H[tata], H[poz]);
            urca(tata);
        }
    }
}

void coboara(int poz)
{
    int st = poz * 2 + 1;
    int dr = poz * 2 + 2;
    int small = poz;
    if (st < L && P[H[st]] < P[H[small]])
        small = st;
    if (dr < L && P[H[dr]] < P[H[small]])
        small = dr;
    if (small != poz)
    {
        swap(H[poz], H[small]);
        coboara(small);
    }
}

void push(int x)
{
    H[L] = x;
    urca(L);
    L ++;
}

int peek()
{
    return P[H[0]];
}

void pop(int poz)
{
    for (int i = 0; i < L; ++i)
    {
        if (H[i] == poz - 1)
        {
            swap(H[i], H[L - 1]);
            L --;
            coboara(i);
        }
    }
}


int main()
{
    fin >> N;
    for (int i = 0; i < N; ++i)
    {
        fin >> op;
        switch(op)
        {
        case 1:
            {
                fin >> x;
                P[nr] = x;
                push(nr);
                nr ++;
                break;
            }
        case 2:
            {
                fin >> x;
                pop(x);
                break;
            }
        case 3:
            {
                fout << peek() << "\n";
                break;
            }
        }
    }
    return 0;
}