Cod sursa(job #2636400)

Utilizator BAlexandruBorgovan Alexandru BAlexandru Data 17 iulie 2020 19:14:47
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.34 kb
#include <fstream>

using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

struct heap
{
    int n;
    int h[200001];
    int pos1[200001], pos2[200001];

    int size()
    {
        return n;
    }

    int getMin()
    {
        return h[1];
    }

    int leftChild(int node)
    {
        return node * 2;
    }

    int rightChild(int node)
    {
        return node * 2 + 1;
    }

    int parent(int node)
    {
        return node / 2;
    }

    void sift(int node)
    {
        int child = 0;
        do
        {
            child = 0;

            if (leftChild(node) <= n)
            {
                child = leftChild(node);

                if (rightChild(node) <= n && h[rightChild(node)] < h[leftChild(node)])
                    child = rightChild(node);

                if (h[child] >= h[node])
                    child = 0;
            }

            if (child)
            {
                swap(h[node], h[child]);
                swap(pos2[pos1[node]], pos2[pos1[child]]);
                swap(pos1[node], pos1[child]);
                node = child;
            }

        }while (child);
    }

    void percolate(int node)
    {
        while (node > 1 && h[node] < h[parent(node)])
        {
            swap(h[node], h[parent(node)]);
            swap(pos2[pos1[node]], pos2[pos1[parent(node)]]);
            swap(pos1[node], pos1[parent(node)]);
            node = parent(node);
        }
    }

    void insertKey(int key, int p)
    {
        n++;
        h[n] = key;
        pos1[n] = p;
        pos2[p] = n;
        percolate(n);
    }

    void deleteKey(int node)
    {
        h[node] = h[n];
        pos2[pos1[n]] = node;
        pos1[node] = pos1[n];
        n--;

        if (node > 1 && h[node] < h[parent(node)])
            percolate(node);
        else
            sift(node);
    }
};

int n, x, y;
heap H;

int main()
{
    f >> n;
    int n1 = 0;
    for (int i=1; i<=n; i++)
    {
        f >> x;
        if (x == 1)
        {
            n1++;
            f >> y;
            H.insertKey(y, n1);
        }
        else if (x == 2)
        {
            f >> y;
            H.deleteKey(H.pos2[y]);
        }
        else if (x == 3)
            g << H.getMin() << "\n";
    }
    return 0;
}