Cod sursa(job #1317600)

Utilizator alexandru.ghergutAlexandru-Gabriel Ghergut alexandru.ghergut Data 15 ianuarie 2015 00:00:47
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.43 kb
#include <fstream>

using namespace std;

#define maxN 200000

int heap[maxN], order[maxN], heapPos[maxN];

int parent(int i);
int leftSon(int i);
int rightSon(int i);
void heapInsert(int x, int &heapK, int &orderK);
void siftUp(int i);
void siftDown(int i, int N);
void heapDelete(int x, int &heapK);

int main()
{
    int N, i, code, x;
    ifstream f("heapuri.in");
    f >> N;

    ofstream g("heapuri.out");
    int heapK = -1, orderK = -1;
    for (i = 1; i <= N; i++)
    {
        f >> code;
        if (code == 1)
        {
            f >> x;
            heapInsert(x, heapK, orderK);
        }
        else if (code == 2)
        {
            f >> x;
            x--;
            heapDelete(x, heapK);
        }
        else if (code == 3)
            g << order[heap[0]] << "\n";
    }

    f.close();
    g.close();
    return 0;
}

int parent(int i)
{
    return (i - 1) / 2;
}

int leftSon(int i)
{
    return i * 2 + 1;
}

int rightSon(int i)
{
    return i * 2 + 2;
}

void heapInsert(int x, int &heapK, int &orderK)
{
    order[++orderK] = x;
    heap[++heapK] = orderK;
    heapPos[orderK] = heapK;
    siftUp(heapK);
}

void siftUp(int i)
{
    if (i)
    {
        if (order[heap[parent(i)]] > order[heap[i]])
        {
            heapPos[heap[parent(i)]] = i;
            heapPos[heap[i]] = parent(i);
            swap(heap[parent(i)], heap[i]);
            siftUp(parent(i));
        }
    }
}

void siftDown(int i, int N)
{
    if (leftSon(i) <= N && rightSon(i) <= N)
    {
        int m = (order[heap[leftSon(i)]] <= order[heap[rightSon(i)]]) ? leftSon(i) : rightSon(i);
        if (order[heap[i]] > order[heap[m]])
        {
            heapPos[heap[i]] = m;
            heapPos[heap[m]] = i;
            swap(heap[i], heap[m]);
            siftDown(m, N);
        }
    }
    else if (leftSon(i) <= N)
    {
        if (order[heap[i]] > order[heap[leftSon(i)]])
        {
            heapPos[heap[i]] = leftSon(i);
            heapPos[heap[leftSon(i)]] = i;
            swap(heap[i], heap[leftSon(i)]);
            siftDown(leftSon(i), N);
        }
    }
    else if (rightSon(i) <= N)
    {
        if (order[heap[i]] > order[heap[rightSon(i)]])
        {
            heapPos[heap[i]] = rightSon(i);
            heapPos[heap[rightSon(i)]] = i;
            swap(heap[i], heap[rightSon(i)]);
            siftDown(rightSon(i), N);
        }
    }
}

void heapDelete(int x, int &heapK)
{
    heap[heapPos[x]] = heap[heapK--];
    siftDown(heapPos[x], heapK);
}