Cod sursa(job #1856117)

Utilizator jason2013Andronache Riccardo jason2013 Data 24 ianuarie 2017 15:43:46
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.05 kb
#include<bits/stdc++.h>
using namespace std;

const int NMAX = 200000;
int N, K;
int poz[NMAX], heap[NMAX], v[NMAX], nr;


inline int father(int child)
{ return child / 2; }

inline int left_son(int father)
{ return father*2; }

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

void swap(int x, int y)
{
    int a;
    a = heap[x]; heap[x] = heap[y]; heap[y] = a;
}

void percolate(int nod)
{
    if(nod > 1)
        if(v[ heap[nod] ] < v[ heap[father(nod)] ])
        {
            poz[heap[nod]] = father(nod);
            poz[heap[father(nod)]] = nod;
            swap(nod, father(nod));
            percolate(father(nod));
        }
}

void sift(int nod)
{
    int son;

    son = nod;
    if(left_son(nod) <= K){ if(v[heap[nod]] > v[heap[left_son(nod)]] ) son = left_son(nod);  }
    if(right_son(nod) <= K){ if(v[heap[son]] > v[heap[right_son(nod)]] ) son = right_son(nod); }

    poz[heap[nod]] = son;
    poz[heap[son]] = nod;
    swap(son, nod);
    if(son != nod) sift(son);

}

void pop(int nod)
{
    poz[ heap[nod] ] = K;
    poz[ heap[K] ] = nod;
    swap(nod, K);
    K--;
    sift(nod);
}

void citire()
{
    freopen("heapuri.in","r",stdin);
    freopen("heapuri.out","w",stdout);

    int op, x;
    scanf("%d", &N);
    for(int i = 1; i <= N; i++)
    {
        scanf("%d",&op);
        switch(op)
        {
            case 1:
                {
                    scanf("%d", &v[++nr]);
                    K++;
                    heap[K] = nr;
                    poz[nr] = K;
                    percolate(K);
                    break;
                }
            case 2:
                {
                    scanf("%d", &x);
                    pop(poz[x]);
                    break;
                }
            case 3:
                {
                    printf("%d ", v[heap[1]]);
                    break;
                }
        }
    }
}

void functie_principala()
{
    citire();
}

int main()
{
    functie_principala();

    return 0;
}