Cod sursa(job #2614203)

Utilizator michael_blazemihai mihai michael_blaze Data 11 mai 2020 14:05:43
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#define MAX 200005

using namespace std;

int minHeap[MAX], n;
int order[MAX], i;
int val[MAX];

int getRoot() {
	return minHeap[1];
}

void upHeap(int x) {
	int father = n / 2;
	if (father and minHeap[father] > minHeap[x]) {
		swap(minHeap[father], minHeap[x]);
		swap(order[val[father]], order[val[x]]);
		upHeap(father);
	}
}

void downHeap(int x) {
	int son = 2 * x;
	if (son + 1 <= n and minHeap[son] > minHeap[son + 1]) 
		son ++;
	
	if (son <= n and minHeap[son] < minHeap[x]) {
		swap(minHeap[son], minHeap[x]);
		swap(order[val[son]], order[val[x]]);
		downHeap(son);
	}
}

int Insert(int x) {
	++ n;
	order[++ i] = n;
	val[n] = i;
	minHeap[n] = x;
	upHeap(n);
}

int Delete(int x) {
	swap(minHeap[n], minHeap[x]);
	swap(order[val[n]], order[val[x]]);
	n --;
	downHeap(x);
}

int main() {
	freopen("heapuri.in", "r", stdin);
	freopen("heapuri.out", "w", stdout);

	int t;
	int operation;
	int value;

	cin >> t;
	while (t --) {
		cin >> operation;

		switch(operation) {
			case 1:
				cin >> value;
				Insert(value);
				break;
			case 2:
				cin >> value;
				Delete(order[value]);
				break;
			case 3:
				cout << getRoot() << '\n';
				break;
		}
	}

	return 0;
}