Cod sursa(job #1000555)

Utilizator lukkerLiNoimi Semain lukker Data 23 septembrie 2013 10:09:46
Problema Heapuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 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 child(int x, int h) {
	return x-pow(h)+1;
}

int parent(int x, int h) {
	return pow(h-1)+(child(x,h)/2+child(x,h)%2)-1;
}

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

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);
}

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;
}