Cod sursa(job #1401449)

Utilizator cautionPopescu Teodor caution Data 25 martie 2015 21:41:49
Problema Heapuri Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 2.04 kb
#include <fstream>
#include <iostream>
#define MAX_N 200005
using namespace std;
long heap[MAX_N];
long right_to_left[MAX_N], left_to_right[MAX_N];
long counter, total;
inline long left_son(long x)
{
    if(x*2<counter)
        return x*2;
    else return x;
}
inline long right_son(long x)
{
    if(x*2+1<counter)
        return x*2+1;
    else return x;
}
inline long father(long x)
{
    return x/2;
}
void interchange(long x1, long x2)
{
    long aux;
    aux=right_to_left[left_to_right[x1]];
    right_to_left[left_to_right[x1]]=right_to_left[left_to_right[x2]];
    right_to_left[left_to_right[x2]]=aux;
    aux=left_to_right[x1];
    left_to_right[x1]=left_to_right[x2];
    left_to_right[x2]=aux;
    aux=heap[x1];
    heap[x1]=heap[x2];
    heap[x2]=aux;
}
void heap_up(long x)
{
    while(heap[father(x)]>heap[x])
    {
        interchange(x, father(x));
        x=father(x);
    }
}
void heap_down(long x)
{
    long aux1, aux2;
    aux1=left_son(x);
    aux2=right_son(x);
    if(heap[x]>heap[aux1]||heap[x]>heap[aux2])
    {
        if(heap[aux1]>heap[aux2]) aux1=aux2;
        interchange(x, aux2);
    }
}
void add(long x)
{
    heap[counter]=x;
    right_to_left[total]=counter;
    left_to_right[counter]=total;
    heap_up(counter);
    ++total;
    ++counter;
}
void erase(long x)
{
    --counter;
    x=right_to_left[x];
    interchange(counter, x);
    if(heap[x]<heap[father(x)])
        heap_up(x);
    else if(heap[x]>heap[right_son(x)]||heap[x]>heap[left_son(x)])
        heap_down(x);
}
int main()
{
    ifstream in("heapuri.in");
    ofstream out("heapuri.out");
    long n, x;
    short op;
    in>>n;
    for(long i=0; i<n; ++i)
    {
        in>>op;
        switch(op)
        {
        case 1:
            in>>x;
            add(x);
            break;
        case 2:
            in>>x;
            erase(x-1);
            break;
        case 3:
            out<<heap[0]<<'\n';
            break;
        }
    }
    in.close(); out.close();
    return 0;
}