Cod sursa(job #2545863)

Utilizator mariaghinescu22Ghinescu Maria mariaghinescu22 Data 13 februarie 2020 16:56:47
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int N = 200001;
int tip, no_heap, no_read, no_operations, v[N], heap[N], poz[N];

void change(int p, int q) {
	swap(heap[p], heap[q]);
	poz[heap[p]] = p;
	poz[heap[q]] = q;
}

void up(int p) {
	while (p > 1 && v[heap[p]] < v[heap[p / 2]]) {
		change(p, p / 2);
		p /= 2;
	}
}

void add(int x) {
	heap[++no_heap] = x;
	poz[x] = no_heap;
	up(no_heap);
}

void down(int p) {
	int son_left = 2 * p;
	int son_right = 2 * p + 1;
	int good = p;
	if (son_left <= no_heap && v[heap[son_left]] < v[heap[good]]) good = son_left;
	if (son_right <= no_heap && v[heap[son_right]] < v[heap[good]]) good = son_right;
	if (good != p) {
		change(good, p);
		down(good);
	}
}

void erase(int p) {
	change(no_heap--, p);
	up(p);
	down(p);
}

void afis() {
	for (int i = 1; i <= no_heap; i++) {
		out << heap[i] << ' ';
	}
	out << "\n";
	for (int i = 1; i <= no_heap; i++) {
		out << poz[i] << ' ';
	}
	out << "\n";
}

int main() {
	int del;
	in >> no_operations;
	for (int i = 1; i <= no_operations; i++) {
		//afis();
		in >> tip; 
		if (tip == 1) {
			in >> v[++no_read];
			add(no_read);
		}
		if (tip == 2) {
			in >> del;
			erase(poz[del]);
		}
		if (tip == 3) {
			out << v[heap[1]] << '\n';
		}
	}
	return 0;
}