Cod sursa(job #1749728)

Utilizator meriniucrMeriniuc Razvan- Dumitru meriniucr Data 28 august 2016 17:19:40
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.01 kb
#include <fstream>

std::pair <int, int> heap[200001];
int                  order[200001];
int                  size;

void
add(int x,
    int index)
{
    int i;

    heap[size] = {x, index};
    order[index] = size;

    i = size;
    while ( (i > 1) and
            (heap[i / 2] > heap[i]) )
    {
        std::swap(order[heap[i / 2].second],
                    order[heap[i].second]);
        std::swap(heap[i / 2],
                    heap[i]);
        i /= 2;
    }
}

void
remove(int index)
{
    std::swap(heap[order[index]],
              heap[order[heap[size - 1].second]]);
    std::swap(order[index],
              order[heap[size - 1].second]);

    index = order[heap[size - 1].second];
    --size;

    while (index * 2 + 1 < size)
    {
        if (heap[2 * index] < heap[2 * index + 1])
        {
            std::swap(order[index],
                      order[2 * index]);
            std::swap(heap[index],
                      heap[2 * index]);

            index <<= 1;
        }
        else
        {
            std::swap(order[index],
                      order[index * 2 + 1]);
            std::swap(heap[index],
                      heap[2 * index + 1]);
            index = (index << 1) + 1;
        }
    }

    if (2 * index < size)
    {
        std::swap(order[index],
                  order[2 * index]);
        std::swap(heap[index],
                  heap[2 * index]);
    }
}

int main()
{
    std::ifstream mama("heapuri.in");
    std::ofstream tata("heapuri.out");

    int n;
    int type;
    int x;
    int count;
    
    mama >> n;

    size = 1;
    count = 1;
    for (int index = 1; index <= n; ++index)
    {
        mama >> type;

        if (type < 3)
        {
            mama >> x;

            if (1 == type)
            {
                add(x, count);
                ++size;
                ++count;
            }
            else
            {
                remove(x);
            }
        }
        else
        {
            tata << heap[1].first << '\n';
        }
    }

    return 0;
}