Cod sursa(job #1533775)

Utilizator rangerChihai Mihai ranger Data 22 noiembrie 2015 22:21:07
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
# include <bits/stdc++.h>

using namespace std;

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()
{
    ifstream fin("heapuri.in");
    ofstream fout("heapuri.out");

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