Cod sursa(job #2201176)

Utilizator ianiIani Biro iani Data 3 mai 2018 20:11:45
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.18 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],ap[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]);
            //swap(ap[loc[K]],ap[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)];
        ap[loc[K]] = K;
        K = father(K);
    }

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

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