Cod sursa(job #802167)

Utilizator repp4raduRadu-Andrei Szasz repp4radu Data 25 octombrie 2012 22:50:57
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>
#include <vector>
#include <cstring>

#define MAX 50005
#define INF 0x3f3f3f3f

using namespace std;

int n, k, v[MAX], P[MAX], H[MAX], NH;

inline bool Compare(const int x, const int y)
{
    return v[H[x]] < v[H[y]];
}

inline void Swap(const int x, const int y)
{
    swap(P[H[x]], P[H[y]]);
    swap(H[x], H[y]);
}

void Percolate(const int x)
{
    int dad = x >> 1;
    if(dad && Compare(x, dad))
    {
        Swap(x, dad); Percolate(dad);
    }
}

void Sift(const int x)
{
    int son = x << 1;
    son += (son + 1 <= NH && Compare(son + 1, son));
    if(son <= NH && Compare(son, x))
    {
        Swap(son, x); Sift(son);
    }
}

void Insert(const int x)
{
    H[++NH] = x; P[x] = NH;
    Percolate(P[x]);
}

void Erase(const int x)
{
    Swap(x, NH);
    P[H[NH]] = 0; H[NH--] = 0;
    Sift(x);
}

int main()
{
    ifstream in("heapuri.in"); ofstream out("heapuri.out");
    int n; in>>n;
    while(n--)
    {
        int type; in>>type;
        if(type == 3) out<<v[H[1]]<<"\n";
        else
        {
            int val; in>>val;
            if(type == 1)
            {
                v[++k] = val;
                Insert(k);
            }
            else
                Erase(P[val]);
        }
    } in.close(); out.close();
}