Cod sursa(job #1210828)

Utilizator daniel.amarieiDaniel Amariei daniel.amariei Data 21 iulie 2014 12:54:16
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.27 kb
#include <fstream>
#define SIZE (200000 + 1)
using namespace std;

int V[SIZE]; // The elements
int H[SIZE]; // The heap (it stores the indices of the elements -- V vector)
int P[SIZE]; // The index in the heap of the element inserted at time x
int heap_size, elements;


#define parent(i) (i/2) 

#define left_child(i) (i*2)

#define right_child(i) (i*2+1)

 
void swap_in_heap(int i, int j)
{
    int aux = H[i];
    H[i] = H[j];
    H[j] = aux;
}

void swap_in_positions(int i, int j)
{
    // swap_in_heap() was called first
    P[H[i]] = i;
    P[H[j]] = j;
}

/**
 * Swap two elements in the heap, keeping the invariant for the
 * P vector in the same time.
 */
 
void swap(int i, int j) 
{
    swap_in_heap(i, j);
    swap_in_positions(i, j);
}

void sift_down(int i)
{
    int min = i;
    
    do
    {
        i = min;
    
        int left = left_child(i);
        int right = right_child(i);
        
        if (left <= heap_size && V[H[left]] < V[H[min]])
        {
            min = left;
        }

        if (right <= heap_size && V[H[right]] < V[H[min]])
        {
            min = right;
        }
        
        if (min != i)
        {
            swap_in_heap(min, i);
        }
    } while (min != i);
}

void sift_up(int i)
{
    int max = i;
    
    do
    {
        i = max;
    
        int p = parent(max);
        
        if (p >= 1 && V[H[p]] > V[H[max]])
        {
            max = p;
        }
        
        if (max != i)
        {
            swap(max, i);
        }
    } while (max != i);
}

void insert(int x)
{
    V[++elements] = x;
    H[++heap_size] = elements;
    P[H[heap_size]] = heap_size;
    sift_up(heap_size);
}

void remove(int x)
{
    H[P[x]] = H[heap_size];
    --heap_size;
    sift_down(P[x]);
}

int min_heap()
{
    return V[H[1]];
}


ifstream ifs("heapuri.in");
ofstream ofs("heapuri.out");


int main()
{
    int n;
    ifs >> n;
    
    for (int i = 0; i < n; ++i)    
    {
        int op;
        ifs >> op;
        
        if (op == 3)
        {
            ofs << min_heap() << "\n";
        }
        else
        {
            int x;
            ifs >> x;

            if (op == 2)
            {
                remove(x);       
            }
            else
            {
                insert(x);
            }
        }
    }

    return 0;
}