Cod sursa(job #2512871)

Utilizator radustn92Radu Stancu radustn92 Data 21 decembrie 2019 20:02:12
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.84 kb
#include <cstdio>
#include <algorithm>
using namespace std;
const int NMAX = 200505;

int ops, N, totalInsertions;

struct heapElement {
	int value, originalPos;

	bool operator < (const heapElement& other) {
		return value < other.value;
	}
};

heapElement heap[NMAX];
int entryToPos[NMAX];

void swapPositionsInHeap(int pos1, int pos2) {
	swap(heap[pos1], heap[pos2]);
	entryToPos[heap[pos1].originalPos] = pos1;
	entryToPos[heap[pos2].originalPos] = pos2;
}

void insertHeap(heapElement& newElement) {
	heap[++N] = newElement;
	entryToPos[newElement.originalPos] = N;

	int currentPos = N;
	while (currentPos / 2 > 0 && newElement < heap[currentPos / 2]) {
		swapPositionsInHeap(currentPos, currentPos / 2);
		currentPos /= 2;
	}
}

int getMinimumChild(int pos) {
	if (pos * 2 + 1 <= N && heap[pos * 2 + 1] < heap[pos * 2]) {
		return pos * 2 + 1;
	}
	return pos * 2;
}

void deleteElementOnPos(int pos) {
	swapPositionsInHeap(pos, N);
	N--;

	while (pos * 2 <= N && heap[getMinimumChild(pos)] < heap[pos]) {
		int bestChildIdx = getMinimumChild(pos);
		swapPositionsInHeap(pos, bestChildIdx);
		pos = bestChildIdx;
	}
}

void debugHeap(int node) {
	if (node > N) {
		return;
	}
	printf("NODE on pos %d has (%d, %d)\n", node, heap[node].value, heap[node].originalPos);
	debugHeap(node * 2);
	debugHeap(node * 2 + 1);
}

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

	scanf("%d", &ops);
	int opType, x;
	for (int op = 0; op < ops; op++) {
		scanf("%d", &opType);
		switch(opType) {
			case 1: {
				heapElement newElement;
				scanf("%d", &newElement.value);
				newElement.originalPos = ++totalInsertions;
				insertHeap(newElement);
				break;
			}
			case 2: {
				scanf("%d", &x);
				deleteElementOnPos(entryToPos[x]);
				break;
			}
			case 3: {
				printf("%d\n", heap[1].value);
				break;
			}
		}

		// debugHeap(1);
	}
	return 0;
}