Cod sursa(job #2710203)

Utilizator CRazvaN6Cutuliga Razvan CRazvaN6 Data 22 februarie 2021 09:48:26
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.97 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

int n,x;
long long int num;

const int MAX_HEAP_SIZE = 16384;
typedef int Heap[MAX_HEAP_SIZE];
Heap H;
int N,v[10001],poz;
inline int father(int nod)
{
    return nod / 2;
}

inline int left_son(int nod)
{
    return nod * 2;
}

inline int right_son(int nod)
{
    return nod * 2 + 1;
}
void sift(Heap H, int N, int K)
{
    int son;
    do
    {
        son = 0;
        // Alege un fiu mai mare ca tatal.
        if (left_son(K) <= N)
        {
            son = left_son(K);
            if (right_son(K) <= N && H[right_son(K)] > H[left_son(K)])
            {
                son = right_son(K);
            }
            if (H[son] <= H[K])
            {
                son = 0;
            }
        }

        if (son)
        {
            swap(H[K], H[son]);  // Functie STL ce interschimba H[K] cu H[son].
            K = son;
        }
    }
    while (son);
}
void percolate(Heap H, int N, int K)
{
    int key = H[K];

    while ((K > 1) && (key > H[father(K)]))
    {
        H[K] = H[father(K)];
        K = father(K);
    }

    H[K] = key;
}
void insert(Heap H, int& N, int key)
{
    H[++N] = key;
    percolate(H, N, N);
}
inline int max(Heap H)
{
    //return H[N];
    v[++poz] = H[N];
}
void cut(Heap H, int& N, int K)
{
    H[K] = H[N];
    --N;

    if ((K > 1) && (H[K] > H[father(K)]))
    {
        percolate(H, N, K);
    }
    else
    {
        sift(H, N, K);
    }
}
int main()
{
    f >> n;
    for(int i = 1; i <= n; ++i)
    {
        f >> x;
        if(x == 1)
        {
            f >> num;
            insert(H,N,num);
        }
        else if(x == 2)
        {
            f >> num;
            cut(H,N,num);
        }
        else if(x == 3) max(H);
    }
    reverse(v+1,v+poz+1);
    for(int i = 1; i <= poz; ++i)
        g << v[i] << '\n';
    return 0;
}