Cod sursa(job #1150232)

Utilizator c0rn1Goran Cornel c0rn1 Data 22 martie 2014 18:29:11
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.58 kb
#include <iostream>
#include <assert.h>
#include <stdio.h>

using namespace std;
int n, h[200010], poz[200010], elemente;

void sift(int p)
{
    int son;
    do
    {
        son=0;
        if (p*2<=n)
        {
            son=p*2;
            if (p*2+1<=n && h[p*2+1]<h[son])
                son++;
            if (h[son]>=h[p])
                son=0;
        }
        if (son)
        {
            swap(h[p], h[son]);
            swap(poz[p], poz[son]);
            p=son;
        }
    }
    while(son);
}

void percolate(int p)
{
    while (p>1 && h[p]<h[p/2])
    {
        swap(h[p], h[p/2]);
        swap(poz[poz[p]], poz[poz[p/2]]);
        p>>=1;
    }
}

void stergere(int x, int p)
{
    h[p]=h[n];
   // poz[p]=poz[poz[n--]];
    int aux;
    for (aux=1; aux<=n; aux++)
        if (poz[aux]==n)
            break;
    poz[aux]=p;
    n--;
    if (p>1 && h[p]<h[p/2])
        percolate(p);
    else
        sift(p);
}

void inserare(int elem)
{
    h[++n]=elem;
    poz[n]=elemente;
    percolate(n);
}

int main()
{
    freopen("heapuri.in", "r", stdin);
    freopen("heapuri.out", "w", stdout);
    int T, x, tip;
    for (scanf("%d", &T); T--;)
    {
        scanf("%d", &tip);
        assert(tip>=1 && tip<=3);
        if (tip==1)
        {
            elemente++;
            scanf("%d", &x);
            inserare(x);
        }
        else if (tip==2)
        {
            scanf("%d", &x);
            stergere(x, poz[x]);
        }
        else
            printf("%d\n", h[1]);
    }
    return 0;
}