Cod sursa(job #2032273)

Utilizator BourucLiviuBouruc Petru Liviu BourucLiviu Data 4 octombrie 2017 19:20:45
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <fstream>

#define N 200005

using namespace std;

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

int A[N], heap[N], pos[N];
int na, nh;

inline int father(int x)
{
    return x/2;
}
inline int left_son(int x)
{
    return x*2;
}
inline int right_son(int x)
{
    return x*2 + 1;
}

inline void percolate(int poz)
{
    while(poz > 1 && A[heap[father(poz)]] > A[heap[poz]])
    {
        swap(heap[father(poz)], heap[poz]);
        swap(pos[heap[father(poz)]], pos[heap[poz]]);
        poz = father(poz);
    }
}

inline void adauga(int x)
{
    A[++na] = x;
    heap[++nh] = na;
    pos[na] = nh;

    percolate(nh);
}

inline void sift(int poz)
{
    int son;
    do
    {
        son = 0;
        if(left_son(poz) <= nh)
        {
            son = left_son(poz);
            if(right_son(poz) <= nh && A[heap[right_son(poz)]] < A[heap[son]]) son = right_son(poz);
        }
        if(son)
        {
            swap(heap[father(poz)], heap[poz]);
            swap(pos[heap[father(poz)]], pos[heap[poz]]);
            poz = son;
        }
    } while(son);
}

inline void sterge(int poz)
{
    heap[poz] = heap[nh];
    pos[poz] = nh;

    sift(nh);
}

int main()
{
    int n, p, x;
    fin >> n;
    while(n--)
    {
        fin >> p;
        if(p == 1 || p == 2) fin >> x;
        switch(p)
        {
            case 1: adauga(x);
                    break;
            case 2: sterge(pos[x]);
                    break;
            default: fout << A[heap[1]] << '\n';
        }
    }
    fin.close(); fout.close();
    return 0;
}