Cod sursa(job #1411345)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 31 martie 2015 17:17:44
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <cstdio>
#include <algorithm>
#include <climits>

#define left (2*nod)
#define right (2*nod+1)

#define val first
#define poz second

using namespace std;

const int Nmax = 200010;

int n , tip , x , nr , in;
int pos[Nmax];
pair < int , int > H[Nmax];

void Swap(int x , int y)
{
    swap(H[x].val , H[y].val);
    swap(H[x].poz , H[y].poz);
    swap(pos[H[x].poz] , pos[H[y].poz]);
}

void HeapUp(int nod)
{
    int up = nod / 2;

    if (H[up].val > H[nod].val)
    {
        Swap(up , nod);
        if (up > 1) HeapUp(up);
    }
}

void HeapDown(int nod)
{
    int min1 = (left <= nr) ? H[left].val : INT_MAX;
    int min2 = (right <= nr) ? H[right].val : INT_MAX;

    if (min(min1 , min2) < H[nod].val)
    {
        if (min1 < min2)
        {
            Swap(left , nod);
            HeapDown(left);
        }
        else
        {
            Swap(right , nod);
            HeapDown(right);
        }
    }
}

int main()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);

    for (scanf("%d", &n); n ; --n)
    {
        scanf("%d", &tip);

        if (tip == 1)
        {
            scanf("%d", &x);
            H[++nr].val = x; H[nr].poz = (++in); pos[in] = nr;
            HeapUp(nr);
        }
        else if (tip == 2)
        {
            scanf("%d", &x); int aux = pos[x];
            Swap(pos[x] , nr); nr--;
            HeapDown(aux);
        }
        else printf("%d\n", H[1].val);
    }

    return 0;
}