Cod sursa(job #2744877)

Utilizator nusmaibunkeleviprofesor cicalescu nusmaibunkelevi Data 25 aprilie 2021 14:21:25
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.77 kb
#include<stdio.h>
#define NM 200001

struct el
{
    int x, id;
};

el h[NM];
int n, poz[NM], nou;

inline int tata(int k)
{
    return k / 2;
}

inline int fiu_st(int k)
{
    return k * 2;
}

inline int fiu_dr(int k)
{
    return k * 2 + 1;
}

inline int min()
{
    return h[1].x;
}

void sift(int k)
{
    int fiu, temp;
    el aux;
    do
    {
        fiu = 0;
        if(fiu_st(k) <= n) fiu = fiu_st(k);
        if(fiu_dr(k) <= n && h[fiu_dr(k)].x < h[fiu_st(k)].x)
            fiu = fiu_dr(k);
        if(h[fiu].x >= h[k].x) fiu = 0;
        if(fiu) temp = poz[h[k].id], poz[h[k].id] = poz[h[fiu].id], poz[h[fiu].id] = temp,
                    aux = h[k], h[k] = h[fiu], h[fiu] = aux,
                                       k = fiu;
    }
    while(fiu);
}

void percolate(int k)
{
    el e = h[k];
    while(k > 1 && e.x < h[tata(k)].x)
    {
        poz[h[tata(k)].id] = k;
        h[k] = h[tata(k)];
        k = tata(k);
    }
    h[k] = e;
    poz[h[k].id] = k;
}

void insert(int x)
{
    h[++n].x = x;
    h[n].id = nou;
    poz[nou] = n;
    percolate(n);
}

void clear(int k)
{
    h[k] = h[n--];
    poz[h[k].id] = k;
    if(k > 1 && h[k].x < h[tata(k)].x) percolate(k);
    else sift(k);
}

int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    int m, tip, x, p;
    scanf("%d", &m);
    while(m--)
    {
        scanf("%d", &tip);
        switch(tip)
        {
        case 1:
            scanf("%d", &x);
            ++nou;
            insert(x);
            break;
        case 2:
            scanf("%d", &p);
            clear(poz[p]);
            break;
        case 3:
            printf("%d\n", min());
        }
    }
    return 0;
}