Cod sursa(job #705841)

Utilizator gener.omerGener Omer gener.omer Data 5 martie 2012 00:25:05
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
#include <cstdio>

using namespace std;

#define NMAX 200005

#define SWAP(a, b){\
    a = a + b;\
    b = a - b;\
    a = a - b;\
}

int A[NMAX], Pos[NMAX], N;

inline int getLeft(int p){ return 2 * p;}
inline int getRight(int p){ return 2 * p + 1;}
inline int getParent(int p){ return p / 2;}
inline int getMin(){ return A[1];}

void down(int p){
	int son;
	do{
		son = 0;
		if(getLeft(p) <= N){
			son = getLeft(p);
			if(getRight(p) <= N && A[son] > A[getRight(p)])
				son = getRight(p);
		}
		if(son){
			if(A[son] < A[p]){
				SWAP(A[son], A[p])
				SWAP(Pos[son], Pos[p])
				p = son;
			}
			else
				son = 0;
		}
	}while(son);
}

void up(int p){
	int key = A[p];
	int initPos = p;
	while((p > 1) && (key < A[getParent(p)])){
		A[p] = A[getParent(p)];
		Pos[getParent(p)] = p;
		p = getParent(p);
	}
	A[p] = key;
	Pos[initPos] = p;
}

void insert(int key){
	++N;
	A[N] = key;
	Pos[N]= N;
	up(N);
}

void build_heap(){
	for(int i = N / 2; i > 0; --i)
		down(i);
}

void cut(int p){
	A[p] = A[N];
	Pos[p] = Pos[N];
	--N;

	if((p > 1) && (A[p] < A[getParent(p)]))
		up(p);
	else
		down(p);
}

int main(){
	freopen("heapuri.in", "r", stdin);
	freopen("heapuri.out", "w", stdout);
	int M;
	scanf("%d", &M);
	for(int i = 0 ; i < M; ++i)	{
		int code, x;
		scanf("%d", &code);
		if(code == 1){
			scanf("%d", &x);
			insert(x);
		}
		else if(code == 2){
			scanf("%d", &x);
			cut(Pos[x]);
		}
		else if(code == 3){
			printf("%d\n", getMin());
		}
	}
	return 0;
}