Cod sursa(job #364898)

Utilizator digital_phreakMolache Andrei digital_phreak Data 17 noiembrie 2009 13:11:01
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#define MAXN 200010
#define INF 1000000010
using namespace std;

// A[i] -> Elementul care o intrat a i-ulea in multime
// Poz[i] -> Poz elementului A[i] in Heap

int A[MAXN];
int Heap[MAXN];
int Poz[MAXN];

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

void push(int x) { // SiftUp
	int aux;
	while (x/2 && A[Heap[x]] < A[Heap[x/2]]) {
		aux = Heap[x];
		Heap[x] = Heap[x/2];
		Heap[x/2] = aux;
		Poz[Heap[x]] = x;
		Poz[Heap[x/2]] = x/2;
		x /= 2;
	}
}

void pop(int x) { // SiftDown
	int aux,left,right,maxInd;
	
	left = x*2;
	right = x*2+1;
	if (left > Heap[0]) {
		if (right > Heap[0]) return;
		maxInd = right;
	} else if (right > Heap[0]) maxInd = left;
	else {
		if (A[Heap[left]] < A[Heap[right]]) maxInd = left;
		else maxInd = right;
	}
	
	aux = Heap[x];
	Heap[x] = Heap[maxInd];
	Heap[maxInd] = aux;
	
	Poz[Heap[x]] = x;
	Poz[Heap[maxInd]] = maxInd;
	
	pop(Poz[Heap[maxInd]]);
}

int main() {
	int K,x,c;

	fin >> K;
	
	while (K--) {
		fin >> c;
		if (c <= 2) {
			fin >> x;
		}
		
		switch (c) {
			case 1:
				A[++A[0]] = x;
				Heap[++Heap[0]] = A[0];
				Poz[A[0]] = Heap[0];
				push(Heap[0]);
				break;
			case 2:
				A[x] = INF;
				pop(Poz[x]);
				--Heap[0];
				break;
			case 3: fout << A[Heap[1]] << "\n"; break;
		}
	}

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