Cod sursa(job #1447717)

Utilizator mouse_wirelessMouse Wireless mouse_wireless Data 5 iunie 2015 02:29:04
Problema Heapuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 kb
#include <cstdio>
#include <cassert>
#include <algorithm>
using namespace std;
#define _submit
#ifdef _submit
#define InFile "heapuri.in"
#define OtFile "heapuri.out"
#else
#define InFile "fis.in"
#define OtFile "fis.out"
#endif

#define MAXN 200010

int heap[MAXN], posInHeap[MAXN], elemNr[MAXN];
int heapSz = 0; int nrElem = 0;

void heapInsert(int x) {
	int curPos = ++heapSz;
	int curElem = ++nrElem;
	heap[curPos] = x;
	posInHeap[curElem] = curPos;
	elemNr[curPos] = curElem;
	while (curPos > 1 && (heap[curPos >> 1] > heap[curPos])) {
		swap(posInHeap[curElem], posInHeap[elemNr[curPos >> 1]]);
		swap(elemNr[curPos >> 1], elemNr[curPos]);
		swap(heap[curPos >> 1], heap[curPos]);
		curPos >>= 1;
	}
}

void heapDelete(int nr) {
	int posHp = posInHeap[nr];
	if (posHp == heapSz) {
		heapSz--;
		return;
	}
	swap(posInHeap[nr], posInHeap[elemNr[heapSz]]);
	swap(elemNr[heapSz], elemNr[posHp]);
	swap(heap[posHp], heap[heapSz]);
	heapSz--;
	int curPos = posHp;
	while (curPos > 1 && (heap[curPos >> 1] > heap[curPos])) {
		swap(posInHeap[elemNr[curPos]], posInHeap[elemNr[curPos >> 1]]);
		swap(elemNr[curPos >> 1], elemNr[curPos]);
		swap(heap[curPos >> 1], heap[curPos]);
		curPos >>= 1;
	}
	while (true) {
		int posToSwap = -1; bool fiu1 = false, fiu2 = false;
		if ((curPos << 1) <= heapSz && heap[curPos] > heap[curPos << 1])
			fiu1 = true;
		if (((curPos << 1) + 1) <= heapSz && heap[curPos] > heap[(curPos << 1) + 1])
			fiu2 = true;
		if (!fiu1 && !fiu2)
			break;
		if (fiu1 && fiu2) {
			if (heap[curPos << 1] < heap[(curPos << 1) + 1])
				posToSwap = curPos << 1;
			else
				posToSwap = (curPos << 1) + 1;
		}
		else if (fiu1)
			posToSwap = curPos << 1;
		else
			posToSwap = (curPos << 1) + 1;
		swap(posInHeap[elemNr[curPos]], posInHeap[elemNr[posToSwap]]);
		swap(elemNr[curPos], elemNr[posToSwap]);
		swap(heap[curPos], heap[posToSwap]);
		curPos <<= posToSwap;
	}
}

int heapTop() {
	return heap[1];
}

int main() {
	assert(freopen(InFile, "r", stdin));
	assert(freopen(OtFile, "w", stdout));
	int N;
	scanf("%d", &N);
	while (N--) {
		int op; int b;
		scanf("%d", &op);
		switch (op) {
		case 1:
			scanf("%d", &b);
			heapInsert(b);
			break;
		case 2:
			scanf("%d", &b);
			heapDelete(b);
			break;
		case 3:
			printf("%d\n", heapTop());
			break;
		default:
			break;
		}
	}
	return 0;
}