Cod sursa(job #2766168)

Utilizator KlinashkaDiacicov Calin Marian Klinashka Data 31 iulie 2021 12:12:19
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <cstdio>
#include <algorithm>
using namespace std;

int A[200001], ind[200001], timp[200001], inserat=0, heapsize=0;

void push(int x, int t) {
	A[++heapsize] = x;
	ind[t] = heapsize; 
	timp[heapsize] = t;
	int i = heapsize;
	while(i>1 && A[i]<A[i/2]) {
		swap(A[i], A[i/2]);
		swap(timp[i], timp[i/2]);
		ind[timp[i]] = i;
		ind[timp[i/2]] = i/2;
		i = i/2;
	}
}

void pop(int x) {
	int idx = ind[x];
	A[idx] = -1;
	swap(A[idx], A[heapsize]);
	swap(timp[idx], timp[heapsize]);
	ind[timp[idx]] = idx;
	ind[timp[heapsize]] = heapsize;
	heapsize--;
	int i = idx;
	do {
		int l=2*i, r=2*i+1, smallest=i;
		if(l<=heapsize && A[l]<A[smallest]) smallest = l;
		if(r<=heapsize && A[r]<A[smallest]) smallest = r;
		if(smallest != i) {
			swap(A[i], A[smallest]);
			swap(timp[i], timp[smallest]);
			ind[timp[i]] = i;
			ind[timp[smallest]] = smallest;
			i = smallest;
		}
		else break;
	}while(true);
}

int main() {
	freopen("heapuri.in", "r", stdin);
	freopen("heapuri.out", "w", stdout);
	int n;
	cin >> n;
	while(n--) {
		int nr;
		cin >> nr;
		if(nr == 1) {
			int x;
			cin >> x;
			push(x, ++inserat);
		}
		else if(nr == 2) {
			int x;
			cin >> x;
			pop(x);
		}
		else {
			cout << A[1] << '\n';
		}
	}
	return 0;
}