Cod sursa(job #1155515)

Utilizator sorin2kSorin Nutu sorin2k Data 26 martie 2014 22:50:21
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include<fstream>
using namespace std;

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

int multime[200001], heap[200001], poz[200001];
int nr_mult, nr_heap;

void swap(int *a, int *b) {
	int aux = *a;
	*a = *b;
	*b = aux;
}

void percolate(int p) {
	int parent = p / 2;
	while(parent >= 1 && multime[heap[parent]] > multime[heap[p]]) {
		swap(heap+p, heap+parent);
		poz[heap[p]] = p;
		poz[heap[parent]] = parent;
		p = parent;
		parent = p/2;
	}
}

void sift(int p) {
	int son;
	son = 2*p;
	if(2*p+1 < nr_heap && multime[heap[2*p+1]] < multime[heap[2*p]]) son = 2*p+1;
	while(son < nr_heap && multime[heap[p]] > multime[heap[son]]) {
		swap(heap+p, heap+son);
		poz[heap[p]] = p;
		poz[heap[son]] = son;
		p = son;
		son = (multime[heap[2*son]] < multime[heap[2*son+1]]) ? 2*son : 2*son+1;
	}
}

void insert(int val) {
	multime[nr_mult] = val;
	heap[nr_heap] = nr_mult;
	poz[nr_mult] = nr_heap;
	nr_mult++;
	nr_heap++;
	percolate(nr_heap-1);
}

void remove(int p) {
	nr_heap--;
	swap(heap+p, heap+nr_heap);
	poz[heap[p]] = p;
	poz[heap[nr_heap]] = nr_heap;

	sift(p);
	percolate(p);
}

void print() {
	int i;
	fout << "p: ";
	for(i = 1; i < nr_heap; i++) {
		fout << heap[i] << " ";
	}
	fout << "\n";
}

int main() {
	int n, i, opt, val;
	nr_heap = nr_mult = 1;
	fin >> n;
	for(i = 0; i < n; i++) {
		fin >> opt;
		if(opt == 1) {
			fin >> val;
			insert(val);
		}
		if(opt == 2) {
			fin >> val;
			remove(poz[val]);
		}
		if(opt == 3) {
			fout << multime[heap[1]] << "\n";
		}
	//	print();
	}
	return 0;
}