Cod sursa(job #2766162)

Utilizator KlinashkaDiacicov Calin Marian Klinashka Data 31 iulie 2021 12:07:26
Problema Heapuri Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 kb
#include <bits/stdc++.h>
using namespace std;

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


void heapify(int i) {
    int smallest = i, l = 2*i, r=2*i+1;
    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;
        heapify(smallest);
    }
}

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];
	swap(A[idx], A[heapsize]);
	swap(timp[idx], timp[heapsize]);
	ind[timp[idx]] = idx;
	ind[timp[heapsize]] = heapsize;
	heapsize--;
	heapify(idx);
}

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];
		}
	}
	return 0;
}