Cod sursa(job #3236653)

Utilizator luc3lexaAlexandrescu Luca luc3lexa Data 30 iunie 2024 01:37:50
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

const int nmax = 2e5+10;
typedef int heap[nmax];

int n,numar_q,operation,value;
int number_elements = 0;
int pos[nmax],values[nmax];
heap h;

inline int father(int nod){
	return nod/2;
}

inline int left_child(int nod){
	return nod*2;
}

inline int right_child(int nod){
	return nod*2+1;
}
inline int minimum_value(heap h){
	return values[h[1]];
}

void heap_down(heap h,int n,int k){
	int son = 0;
	do{
		son = 0;
		if(left_child(k) <= n){
			son = left_child(k);
			if(right_child(k) <=n && values[h[right_child(k)]] < values[h[left_child(k)]]){
				son = right_child(k);
			};
			if(values[h[son]] >= values[h[k]]){
				son = 0;
			}
		};
		if(son){
			swap(h[son],h[k]);
			swap(pos[h[son]],pos[h[k]]);
			k = son;
		}
	}while(son);
};

void heap_up(heap h,int n,int k){
	while(k > 1 && values[h[k]] < values[h[father(k)]]){
		swap(h[k],h[father(k)]);
		swap(pos[h[k]],pos[h[father(k)]]);
		k = father(k);
	}
};

void insert(heap h,int &n,int number){
	values[++number_elements] = number;
	n++;
	pos[number_elements] = n;
	h[n] = number_elements;
	
	heap_up(h,n,n);
}

void erase_element(heap h,int &n,int k){
	swap(h[n],h[k]);
	swap(pos[h[n]],pos[h[k]]);
	n--;
	if(k > 1 && values[h[k]] < values[h[father(k)]]){
		heap_up(h,n,k);
	}else{
		heap_down(h,n,k);
	}
}
int main(){
	fin >> numar_q;
	for(int i = 1; i <=numar_q; i++){
		fin >> operation;
		if(operation == 1){
			fin >> value;
			insert(h,n,value);
		}else if(operation == 2){
			fin >> value;
			erase_element(h,n,pos[value]);
		}else{
			fout << minimum_value(h) << '\n';
		}
	};
	return 0;
}