Cod sursa(job #1171892)

Utilizator tudi98Cozma Tudor tudi98 Data 16 aprilie 2014 15:38:38
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.79 kb
#include <fstream> 
#include <iostream>
#include <algorithm>
#define dim 200001
using namespace std;

typedef int Heap[dim];


inline int father(int K){
	return (K >> 1);
}

inline int left_son(int K){
	return (K << 1);
}

inline int right_son(int K){
	return ((K << 1) + 1);
}

inline int max(Heap& H){
	return H[1];
}


void sift(Heap& H,int& N,int K){
	
	int son=0;
	do{
		int son = 0;
		if(left_son(K) <= N){
			son = left_son(K);
			if((right_son(K) <= N) && (H[son] > H[right_son(K)])){
				son = right_son(K);
			}
			if(H[son] >= H[K]){
				son = 0; 
			}
		}
		
		if(son){
			swap(H[K],H[son]);
			K = son;
		}
	}while(son);
}


void percolate(Heap& H,int& N,int K){

	int key = H[K];

	while((K > 1) && (key < H[father(K)])){
		H[K] = H[father(K)];
		K = father(K);
	}

	H[K] = key;
}


void build_heap(Heap& H,int& N){
	for(int i = (N >> 1); i >= 1; i--){
		sift(H,N,i);
	}
}


void cut(Heap& H,int& N,int K){
	H[K] = H[N--];
	if((K > 1) && (H[father(K)] > H[K])){
		percolate(H,N,K);
	}		
	else{
		sift(H,N,K);
	}
}


void insert(Heap& H,int& N,int key){
	H[++N] = key;
	percolate(H,N,N);
}


int  search(Heap& H,int& N,int key,int K){
	if(H[K] == key) return K;
	int nod=0;
	if((left_son(K) <= N) && (H[left_son(K)] <= key)){
		nod=search(H,N,key,left_son(K));
	}
	if((!nod) && (right_son(K) <= N) && (H[right_son(K)] <= key)){
		nod=search(H,N,key,right_son(K));	
	}
	return nod;
}


int main(){

	ifstream f("heapuri.in");
	ofstream g("heapuri.out");	

	int N=0,n,j=0,a,b,nr[dim],K;
	Heap H;
	
	f >> n;
	for(int i =1 ; i <= n; i++){
		f >> a;
		switch(a){
			case 1: {
		  		f >> b;
				nr[++j] = b;
				insert(H,N,b);
				break;
			}
			case 2: {
				f >> b;
				//cout << "iese "<< nr[b] <<"\n";
				K=search(H,N,nr[b],1);
				cut(H,N,K);
				break;
			}
			case 3: {
				g << max(H) << "\n";
				break;
			}
		}
	}
}