Cod sursa(job #1749751)

Utilizator meriniucrMeriniuc Razvan- Dumitru meriniucr Data 28 august 2016 17:52:01
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.1 kb
#include <fstream>
#include <iostream>

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)
{
    order[heap[size - 1].second] = order[index];
    std::swap(heap[order[index]],
              heap[size - 1]);

    index = order[index];
    --size;

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

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

    if ( (2 * index < size) and
         (heap[index] > heap[2 * index]) )
    {
        std::swap(order[heap[index].second],
                  order[heap[2 * index].second]);
        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;
}