Cod sursa(job #2512903)

Utilizator radustn92Radu Stancu radustn92 Data 21 decembrie 2019 21:07:21
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 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 goUpIfNecessary(int pos) {
	while (pos / 2 > 0 && heap[pos] < heap[pos / 2]) {
		swapPositionsInHeap(pos, pos / 2);
		pos /= 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 goDownIfNecessary(int pos) {
	while (pos * 2 <= N && heap[getMinimumChild(pos)] < heap[pos]) {
		int bestChildIdx = getMinimumChild(pos);
		swapPositionsInHeap(pos, bestChildIdx);
		pos = bestChildIdx;
	}
}

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

	goUpIfNecessary(N);	
}

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

	goUpIfNecessary(pos);
	goDownIfNecessary(pos);
}

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