Cod sursa(job #881020)

Utilizator gener.omerGener Omer gener.omer Data 17 februarie 2013 17:05:30
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.81 kb
#include <iostream>
#include <algorithm>
#include <fstream>

using namespace std;

#define NMAX 200005

int A[NMAX], Heap[NMAX], Pos[NMAX], t = 0, n = 0;

int getLeft(int p){ return 2 * p + 1;}
int getRight(int p){ return 2 * p + 2;}
int getParent(int p){return (p-1)/2;}

int getMin()
{
	return A[Heap[0]];
}

void up(int p)
{
	while(p > 0 && A[Heap[p]] < A[Heap[getParent(p)]]){
		swap(Heap[p], Heap[getParent(p)]);
		Pos[Heap[p]] = p;
		Pos[Heap[getParent(p)]] = getParent(p);
		p = getParent(p);
	}
}

void down(int p)
{
	int son;
	do{
		son = -1;
		if(getLeft(p) < n)
		{
			son = getLeft(p);
			if(getRight(p) < n && A[Heap[son]] > A[Heap[getRight(p)]])
				son = getRight(p);
		}
		
		if(son != -1)
		{
			if(A[Heap[son]] < A[Heap[p]])
			{
				swap(Heap[son], Heap[p]);
				Pos[Heap[son]] = son;
				Pos[Heap[p]] = p;
				p = son;
			}
			else
			{
				son = -1;
			}
		}
		
	}while(son != -1);
}


void insert(int x)
{
	A[t] = x, Pos[t] = n, Heap[n] = t; 
	++t, ++n;
	up(n-1);
}

void del(int x)
{
	A[x] =  1000000001;
	down(Pos[x]);
	--n;
	A[x] = -1;
	
	/*int pos = Pos[x];
    A[x] = -1;
    Pos[x] = -1;
 
    if(pos != (n-1)){
        Heap[pos] = Heap[n--];
        Pos[Heap[pos]] = pos;
 
        if(n > 0){
            if(pos > 1 && A[Heap[pos]] < A[Heap[getParent(pos)]])
                up(pos);
            else
				down(pos);
        }
    }
    else
        --n;*/
}

int main()
{
	ifstream in("heapuri.in");
	ofstream out("heapuri.out");
	
	int nr_op;
	
	in >> nr_op;
	for(int i = 0; i < nr_op;++i)
	{
		int code, x;
		in >> code;
		if(code == 1)
		{
			in >> x;
			insert(x);
		}
		else if(code == 2)
		{
			in >> x;
			del(x-1);
		}
		else if(code == 3)
		{
			out << getMin() << endl;
		}
	}
	return 0;
}