Cod sursa(job #2198021)

Utilizator ianiIani Biro iani Data 23 aprilie 2018 13:12:07
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.2 kb
#include <iostream>
#include <fstream>

using namespace std;

const int MAX_HEAP_SIZE = 200005;
typedef int Heap[MAX_HEAP_SIZE];
int loc[MAX_HEAP_SIZE];

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

inline int mini(Heap H)
{
    return H[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].
            swap(loc[K],loc[son]);
            K = son;
        }
    }
    while (son);
}

void percolate(Heap H, int N, int K)
{
    int key = H[K];
    int lockey = K;

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

    H[K] = key;
    loc[K]= lockey;
}

void hinsert(Heap H, int& N, int key)
{
    H[++N] = key;
    loc[N] = N;
    percolate(H, N, 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 fct(int x,int N)
{
    for (int i=0; i<N; i++)
        if (loc[i]==x)
            return i;
    return 0;
}

int main()
{
    ifstream fin ("heapuri.in");
    ofstream fout ("heapuri.out");
    Heap H;
    int nrin,n=0;
    fin>>nrin;
    for (int var=0; var<nrin; var++)
    {
        int x;
        char cer;
        fin>>cer;
        if (cer=='3')
            fout<<mini(H)<<'\n';
        else
        {
            fin>>x;
            if (cer=='1')
                hinsert(H,n,x);
            if (cer=='2')
                cut(H,n,fct(x,n));
        }
    }
    return 0;
}