Cod sursa(job #1555898)

Utilizator TimitocArdelean Andrei Timotei Timitoc Data 23 decembrie 2015 18:05:16
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.15 kb
#include <iostream>
#include <cstdio>
#define MAX_SIZE 200050
#define inf 1000100000

using namespace std;

int posa[MAX_SIZE]; /// posa[i] = pozitia i-lui element in heap
int posh[MAX_SIZE]; /// posh[i] = pozitia elementului i din heap in a
int a[MAX_SIZE], sz; /// a[i] a i-a valoare inserata

struct MinHeap
{
    int a[MAX_SIZE], n;
    MinHeap()
    {
        a[0] = -inf;
        n = 0;
    }

    void percolate(int ind)
    {
        int val = a[ind], inh = posh[ind];
        while (val < a[ind>>1]) {
            a[ind] = a[ind>>1];
            posa[posh[ind>>1]] = ind;
            posh[ind] = posh[ind>>1];
            ind >>= 1;
        }
        a[ind] = val;
        posh[ind] = inh;
        posa[inh] = ind;
    }

    void sift(int ind)
    {
        int val = a[ind], inh = posh[ind];
        while ((ind<<1) <= n)
        {
            int k = ind<<1;
            if (k+1 <= n && a[k+1] < a[k])
                ++k;
            if (val < a[k]) break;
            a[ind] = a[k];
            posa[posh[k]] = ind;
            posh[ind] = posh[k];
            ind = k;
        }
        a[ind] = val;
        posh[ind] = inh;
        posa[inh] = ind;
    }

    void insert(int x)
    {
        a[++n] = x;
        posa[sz] = n;
        posh[n] = sz;
        percolate(n);
    }

    void cut(int pos)
    {
        swap(posa[posh[pos]], posa[posh[n]]);
        swap(posh[n], posh[pos]);
        a[pos] = a[n--];
        if (a[pos] < a[pos>>1])
            percolate(pos);
        else
            sift(pos);
    }

    int getMin()
    {
        return a[1];
    }
};
MinHeap heap;

void debug()
{
    for (int i = 1; i <= sz; i++)
        fprintf(stderr, "%d", posa[i]);
    fprintf(stderr, "\n");
}

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

    int nr, tip, x;
    scanf("%d", &nr);
    for (int i = 1; i <= nr; i++)
    {
        scanf("%d", &tip);
        if (tip == 1) {
            scanf("%d", &a[++sz]);
            heap.insert(a[sz]);
        }
        else if (tip == 2) {
            scanf("%d", &x);
            heap.cut(posa[x]);
        }
        else
            printf("%d\n", heap.getMin());
    }
    return 0;
}