Cod sursa(job #1547123)

Utilizator Nevermore10Macovei Cosmin Nevermore10 Data 9 decembrie 2015 01:54:06
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <iostream>
using namespace std;

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

int n, heap_size;
int heap[200005];
int cnt;
int pos_heap[200005]; // pozitia in heap a elementului intrat al i-lea
int pos_arr[200005];

void Swap(int p1, int p2)
{
     int a1 = pos_arr[p1];
     int a2 = pos_arr[p2];

     swap(heap[p1], heap[p2]);
     pos_arr[p2] = a1;
     pos_heap[a1] = p2;

     pos_arr[p1] = a2;
     pos_heap[a2] = p1;
}

void urca(int pos)
{
    while (pos > 1 && heap[pos] < heap[pos/2])
        Swap(pos, pos/2), pos/=2;
}

void coboara(int pos)
{
    while (2 * pos <= heap_size)
    {
        int son = 2*pos;
        if (2*pos+1<=heap_size && heap[2*pos+1]<heap[son]) son++;

        if (heap[pos]>heap[son]) Swap(pos, son), pos = son;
        else break;
    }
}

void ins(int val)
{
    heap[++heap_size] = val;
    pos_heap[cnt] = heap_size;
    pos_arr[heap_size] = cnt;
    urca(heap_size);
}

void del(int pos)
{
     Swap(pos, heap_size);
     heap_size--;
     if (heap[pos] < heap[pos/2]) urca(pos);
     else coboara(pos);
}

int main()
{
    f>>n;
    while (n--) {
        int op, x;
        f>>op;
        if (op == 1) {
            cnt++;
            f>>x;
            ins(x);
        }
        if (op == 2) {
            f>>x;
            del(pos_heap[x]);
        }
        if (op == 3)
            g<<heap[1]<<"\n";
    }
    return 0;
}