Cod sursa(job #1376118)

Utilizator radarobertRada Robert Gabriel radarobert Data 5 martie 2015 16:04:56
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>

using namespace std;

const int MAXN = 200000;

int heap[MAXN], in_heap[MAXN], v[MAXN];
int heap_size = 0;

void swapValues(int a, int b)
{
    int t = heap[a];
    heap[a] = heap[b];
    heap[b] = t;
    in_heap[heap[a]] = a;
    in_heap[heap[b]] = b;
}

void addToHeap(int n)
{
    heap[++heap_size] = n;
    in_heap[n] = heap_size;
    int i = heap_size;
    while (v[heap[i]] < v[heap[i/2]] && i > 1)
    {
        swapValues(i, i/2);
        i = i/2;
    }
}

void deleteFromHeap(int n)
{
    int p = in_heap[n];
    in_heap[n] = 0;
    heap[p] = heap[heap_size];
    --heap_size;
    in_heap[heap[p]] = p;
    int i = p;
    int vmin;
    while (1)
    {
        vmin = i;
        if (2*i <= heap_size && v[heap[2*i]] < v[heap[vmin]])
            vmin = 2*i;
        if (2*i+1 <= heap_size && v[heap[2*i+1]] < v[heap[vmin]])
            vmin = 2*i+1;
        if (i != vmin)
        {
            swapValues(i, vmin);
            i = vmin;
        }
        else
            break;
    }
}

int main()
{
    ifstream in("heapuri.in");
    ofstream out("heapuri.out");

    int n;
    in >> n;
    int t, x;
    int nr = 0;
    for (int i = 1; i <= n; i++)
    {
        in >> t;
        if (t == 1)
        {
            ++nr;
            in >> x;
            v[nr] = x;
            addToHeap(nr);
        }
        else if (t == 2)
        {
            in >> x;
            deleteFromHeap(x);
        }
        else if (t == 3)
        {
            out << v[heap[1]] << '\n';
        }
    }

    return 0;
}