Cod sursa(job #3211707)

Utilizator AlbuDariusAlbu Darius AlbuDarius Data 10 martie 2024 08:33:13
Problema Heapuri Scor 20
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <fstream>

using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int h[200005], n, elem[200005];
int father(int nod) {
    return nod / 2;
}
int left_son(int nod) {
    return nod * 2;
}
int right_son(int nod) {
    return nod * 2 + 1;
}

void sift(int x);
void percolate(int x);
void inserare(int x);
void sterge(int x);
int main()
{
    int operatie, x, n1, m = 0;
    fin >> n1;
    for (int i = 1; i <= n1; i++) {
        fin >> operatie;
        if (operatie == 1) {
            fin >> x;
            elem[++m] = x;
            inserare(x);
        }
        else if (operatie == 2) {
            fin >> x;
            if (h[1] == elem[x])
                sterge(1);
            else {
                for (int j = 2; j <= n; j *= 2)
                    if (h[j] == elem[x]) {
                        sterge(j);
                        break;
                    }
                    else if (h[j + 1] == elem[x]) {
                        sterge(j + 1);
                        break;
                    }
            }
        }
        else
            fout << h[1] << "\n";
    }
    return 0;
}
void sift(int x)
{
    int son;
    do {
        son = 0;
        if (left_son(x) <= n) {
            son = left_son(x);
            if (right_son(x) >= n && h[right_son(x)] < h[left_son(x)])
                son = right_son(x);
            if (h[son] >= h[x])
                son = 0;
        }
        if (son) {
            swap(h[x], h[son]);
            x = son;
        }
    }while (son);
}
void percolate(int x)
{
    int key = h[x];
    while (x > 1 && key < h[father(x)]) {
        h[x] = h[father(x)];
        x = father(x);
    }
    h[x] = key;
}
void inserare(int x)
{
    h[++n] = x;
    percolate(n);
}
void sterge(int x)
{
    h[x] = h[n];
    n--;
    if (x > 1 && h[x] < h[father(x)])
        percolate(x);
    else
        sift(x);
}