Cod sursa(job #1444520)

Utilizator DrumeaVDrumea Vasile DrumeaV Data 29 mai 2015 20:59:58
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include <stdio.h>
#include <vector>
using namespace std;

const int Max = 200005;
int H[Max],Pos[Max],Inx[Max],N,M,Nr;

inline int Dad(int Node)
{
    return Node / 2;
}

inline int LS(int Node)
{
    return Node * 2;
}

inline int RS(int Node)
{
    return Node * 2 + 1;
}

void sift(int Node)
{
    int Son;
    do
    {
        Son = 0;
        if (LS(Node) <= M) Son = LS(Node);
        if (RS(Node) <= M && H[RS(Node)] < H[LS(Node)]) Son = RS(Node);
        if (H[Node] <= H[Son]) Son = 0;

        if (Son)
        {
             swap(H[Node],H[Son]);
             Pos[Inx[Node]] = Son;
             Pos[Inx[Son]] = Node;
             swap(Inx[Node],Inx[Son]);
            Node = Son;
        }
    }while (Son);
}

void percolate(int Node)
{
    while (Node > 1 && H[Node]<H[Dad(Node)])
    {
        swap(H[Node],H[Dad(Node)]);
        Pos[Inx[Node]] = Dad(Node);
        Pos[Inx[Dad(Node)]] = Node;
        swap(Inx[Node],Inx[Dad(Node)]);
        Node = Dad(Node);
    }
}

void Del_N(int Node)
{
    H[Node] = H[M];
    Pos[Inx[M]] = Node;
    Inx[Node] = Inx[M];
    M--;

    if (Node > 1 && H[Node] > H[Dad(Node)])
        percolate(Node);
    else
        sift(Node);
}


int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);
     scanf("%d",&N);
     int X;
     char O;

     for (int i = 1;i <= N;i++)
     {
         scanf("%d",&O);
         if (O < 3) scanf("%d",&X);
         switch (O)
         {
             case 1:
                 {
                     Nr++;
                     H[++M] = X;
                     Pos[Nr] = M;
                     Inx[M] = Nr;
                     percolate(M);
                     break;
                 }
             case 2:
                 {
                     Del_N(Pos[X]);
                     break;
                 }
             case 3:
                 {
                      printf("%d\n",H[1]);
                      break;
                 }
         }
     }
    return 0;
}