Cod sursa(job #1000561)

Utilizator lukkerLiNoimi Semain lukker Data 23 septembrie 2013 10:40:05
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>
using namespace std;

int heap[200001];
int poz[200001];
int ph[200001];
int lenght = 0;
int last = 0;

int pow(int x) {
	int y = 1;
	while(x-->0) y*=2;
	return y;
}

int lc(int x) {
	return x*2;
}

int rc(int x) {
	return x*2+1;
}

int parent(int x) {
	return x/2;
}

void swap(int p, int x) {
	int aux = heap[p];
	heap[p] = heap[x];
	heap[x] = aux;
	aux = poz[ph[p]];
	poz[ph[p]] = poz[ph[x]];
	poz[ph[x]] = aux;
	aux = ph[p];
	ph[p] = ph[x];
	ph[x] = aux;
}

void verify(int x) {
	int h=0; // nivelul in heap
	while(pow(h+1)<x) h++;
	int p = parent(x);
	if(heap[p]>heap[x]) {
		swap(p,x);
		verify(p);
	}
}

void down(int x) {
	if(x>lenght) return;
	if(lc(x)<rc(x)) {
		swap(lc(x),x);
		down(lc(x));
	} else {
		swap(rc(x),x);
		down(rc(x));
	}
}

void insert(int x) {
	heap[++lenght] = x;
	poz[++last] = lenght;
	ph[lenght] = last;
	verify(lenght);
}

void pop(int x) {
	heap[poz[x]] = heap[lenght--];
	poz[x] = lenght--;
	verify(x);
	down(x);
}

int main() {
	int n;
	int o, p;
	ifstream f("heapuri.in");
	ofstream fout("heapuri.out");
	f>>n;
	while(n-->0) {
		f>>o;
		if(o==1) {f>>p;insert(p);}
		if(o==2) {f>>p;pop(p);}
		if(o==3) fout<<heap[1]<<endl;
	}
	
	return 0;
}