Cod sursa(job #3318778)

Utilizator DobraVictorDobra Victor Ioan DobraVictor Data 28 octombrie 2025 19:33:54
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.31 kb
#include <iostream>
#include <fstream>
#include <stdint.h>

const int32_t MAX_N = 200000;

int32_t vals[MAX_N], pos[MAX_N], top = 0;
int32_t heap[MAX_N + 1], heapSize = 0;

void PushHeap(int32_t ind) {
	heap[++heapSize] = ind;
	pos[ind] = heapSize;

	for(int32_t i = heapSize; i != 1; i >>= 1) {
		if(vals[heap[i]] < vals[heap[i >> 1]]) {
			std::swap(pos[heap[i]], pos[heap[i >> 1]]);
			std::swap(heap[i], heap[i >> 1]);
		} else {
			break;
		}
	}
}
void PopHeap(int32_t ind) {
	int32_t startPos = pos[ind];

	std::swap(pos[heap[startPos]], pos[heap[heapSize]]);
	std::swap(heap[startPos], heap[heapSize]);
	--heapSize;

	if(startPos != 1 && vals[heap[startPos]] < vals[heap[startPos >> 1]]) {
		for(int32_t i = startPos; i != 1; i >>= 1) {
			if(vals[heap[i]] < vals[heap[i >> 1]]) {
				std::swap(pos[heap[i]], pos[heap[i >> 1]]);
				std::swap(heap[i], heap[i >> 1]);
			} else {
				break;
			}
		}
	} else {
		for(int32_t i = startPos; i <= heapSize;) {
			int32_t child1 = i << 1, child2 = (i << 1) + 1;

			if(child1 <= heapSize && child2 <= heapSize) {
				if(vals[heap[child1]] >= vals[heap[i]] && vals[heap[child2]] >= vals[heap[i]])
					break;

				if(vals[heap[child1]] < vals[heap[child2]]) {
					std::swap(pos[heap[child1]], pos[heap[i]]);
					std::swap(heap[child1], heap[i]);
					i = child1;
				} else {
					std::swap(pos[heap[child2]], pos[heap[i]]);
					std::swap(heap[child2], heap[i]);
					i = child2;
				}

				continue;
			}

			if(child1 <= heapSize && vals[heap[child1]] < vals[heap[i]]) {
				std::swap(pos[heap[child1]], pos[heap[i]]);
				std::swap(heap[child1], heap[i]);
				i = child1;
			} else if(child2 <= heapSize && vals[heap[child2]] < vals[heap[i]]) {
				std::swap(pos[heap[child2]], pos[heap[i]]);
				std::swap(heap[child2], heap[i]);
				i = child2;
			} else {
				break;
			}
		}
	}
}

int main() {
	std::ifstream fin("heapuri.in");
	std::ofstream fout("heapuri.out");

	int32_t n;
	fin >> n;

	for(int32_t i = 0; i != n; ++i) {
		int32_t c;
		fin >> c;

		if(c == 1) {
			int32_t x;
			fin >> x;
			vals[top++] = x;
			PushHeap(top - 1);
		} else if(c == 2) {
			int32_t x;
			fin >> x;
			--x;
			PopHeap(x);
		} else {
			fout << vals[heap[1]] << '\n';
		}
	}

	fin.close();
	fout.close();

	return 0;
}