Cod sursa(job #933497)

Utilizator siminescuPaval Cristi Onisim siminescu Data 30 martie 2013 00:27:14
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
/*
 * heapuri.cpp
 *
 *  Created on: 29.03.2013
 *      Author: Cristi
 */

#include<fstream>
#include <iostream>
using namespace std;

#define nmax 200002
ifstream f("heapuri.in");
ofstream g("heapuri.out");

long long P[nmax], H[nmax], I[nmax], N, cron;

int leftSon(int pos) {

	return 2 * pos + 1;
}

int rightSon(int pos) {

	return 2 * (pos + 1);
}

int father(int pos) {

	return (pos - 1) / 2;
}

void swap(int a,int b)
{
	int key=H[a], keypoz=P[I[a]], keynri=I[a];
	H[a] = H[b];
	P[I[a]] = P[I[b]];
	I[a] = I[b];
	H[b] = key;
	P[I[b]] = keypoz;
	I[b] = keynri;
}

void percolate(int pos) {

	while (H[pos] < H[father(pos)]) {
		swap(pos, father(pos));
		pos = father(pos);
		if (pos == 0)
			break;
	}
}

void addElement(long long e) {

	H[N] = e;
	P[++cron] = N;
	I[N] = cron;
	N++;
	percolate(N - 1);
}

int posOfMinimSon(int pos) {

	int posMin = pos;
	if(leftSon(pos) < N && H[leftSon(pos)] < H[pos]) {
		posMin = leftSon(pos);
	}
	if (rightSon(pos) < N && H[rightSon(pos)] < H[posMin])
		posMin = rightSon(pos);
	return posMin;
}

void sift(int pos) {

	while (posOfMinimSon(pos) < N) {
		if (H[pos] <= H[posOfMinimSon(pos)])
			break;
		swap(pos, posOfMinimSon(pos));
		pos = posOfMinimSon(pos);
	}
}

void removeElement(int indecs) {

	int pos = P[indecs];
	swap(pos, N - 1);
	N--;
	sift(pos);
}

void printMinim() {

	cout << H[0] << '\n';
}

int main() {

	int M, opp;
	long long x;

	f >> M;

	for (; M; --M) {

		f >> opp;
		if (opp == 1) {
			f >> x;
			addElement(x);
		} else if (opp == 2) {
			f >> x;
			removeElement(x);
		} else {
			printMinim();
		}
	}
	return 0;
}