Cod sursa(job #1455818)

Utilizator fluture.godlikeGafton Mihnea Alexandru fluture.godlike Data 29 iunie 2015 10:09:18
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
#include <cstdio>
#include <algorithm>
#define NMAX 200007
using namespace std;
int h[NMAX], hp[NMAX], ord[NMAX], ct;
int father(int x)
{
    return x/2;
}
int left(int x)
{
    return 2*x;
}
int right(int x)
{
    return 2*x+1;
}
int hmin()
{
    return h[1];
}
void upheap(int pos)
{
    while(father(pos) >= 1 && h[pos] < h[father(pos)])
    {
        swap(h[pos], h[father(pos)]);
        swap(hp[h[pos]], hp[h[father(pos)]]);
        pos = father(pos);
    }
}
void downheap(int pos)
{
    int best = pos;
    if(left(pos) <= h[0])
    {
        if(h[left(pos)] < h[pos])
        {
            best = left(pos);
        }
    }
    if(right(pos) <= h[0])
    {
        if(h[right(pos)] < h[pos])
        {
            best = right(pos);
        }
    }
    while(best!=pos)
    {
        swap(h[best], h[pos]);
        swap(hp[h[best]], hp[h[pos]]);
        pos = best;
        if(left(pos) <= h[0])
        {
            if(h[left(pos)] < h[pos])
            {
                best = left(pos);
            }
        }
        if(right(pos) <= h[0])
        {
            if(h[right(pos)] < h[pos])
            {
                best = right(pos);
            }
        }
    }
}
void hinsert(int x)
{
    h[0]++;
    h[h[0]] = x;
    hp[x] = h[0];
    upheap(h[0]);

}
void herase(int pos)
{
    swap(h[pos], h[h[0]]);
    swap(hp[h[pos]], hp[h[h[0]]]);
    h[0]--;
    downheap(pos);
}
FILE *fin, *fout;
int n, p, k;
int main()
{
    fin = freopen("heapuri.in", "r", stdin);
    fout = freopen("heapuri.out", "w", stdout);
    scanf("%d", &n);
    for(int i = 1; i<= n; i++)
    {
        scanf("%d", &p);
        if(p == 1)
        {
            scanf("%d", &k);
            hinsert(k);
            ct++;
            ord[ct] = k;
        }
        if(p == 2)
        {
            scanf("%d", &k);
            herase(hp[ord[k]]);
        }
        if(p == 3)
        {
            printf("%d\n", hmin());
        }
    }
    printf("\n");
    fclose(fin);
    fclose(fout);
    return 0;
}