Cod sursa(job #2552257)

Utilizator ViAlexVisan Alexandru ViAlex Data 20 februarie 2020 18:32:24
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.74 kb
#include<bits/stdc++.h>
using namespace std;


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

int query_count;


struct heap{
	int elements[300000];
	int chrono[300000];
	int which[300000];
	int size;
	int added;


	heap():size(0),added(0){

	}

	int top(){
		return elements[0];
	}

	int left(int node){
		return node*2;
	}
	int right(int node){
		return node*2+1;
	}
	int father(int node){
		return node/2;
	}
	int change(int a,int b){
		swap(elements[a],elements[b]);
		which[chrono[a]]=b;
		which[chrono[b]]=a;
		swap(chrono[a],chrono[b]);

	}

	void sift(int node){

		int son;
		do{
			son=0;


			if(left(node)<size){
				son=left(node);
				if(right(node)<size && elements[right(node)]<elements[son]){
					son=right(node);
				}

				if(elements[son]>=elements[node])
					son=0;
			}

			if(son){
				change(node,son);
				node=son;
			}
		}
		while(son);

	}



	void percolate(int node){

		while(node && elements[father(node)]>elements[node]){
			change(father(node),node);
			node=father(node);
		}
	}



	void insert(int value){//adds a new element to the heap

		chrono[size]=added;
		which[added]=size;

		added++;



		elements[size++]=value;
		percolate(size-1);


		
	}

	void cut(int index){//removes the given index from the heap


		elements[index]=elements[size-1];
		size--;
		if(index&& elements[index]<elements[father(index)])
			percolate(index);
		else sift(index);
	}


};


void read(){
	in>>query_count;
}


void solve(){
	heap minheap;
	int query_type,aux;

	for(int i=0;i<query_count;i++){
		in>>query_type;

		if(query_type==1){
			in>>aux;
			minheap.insert(aux);
		}
		else if(query_type==2){
			in>>aux;
			minheap.cut(minheap.which[aux-1]);
		}
		else{
			out<<minheap.top()<<'\n';
		}


	}

}



int main(){
	read();
	solve();
}