Cod sursa(job #1577037)

Utilizator casuneanu.andreiCasuneanu Andrei Dan casuneanu.andrei Data 23 ianuarie 2016 10:31:35
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <iostream>
#define IN "heapuri.in"
#define OUT "heapuri.out"
#define DMAX 200000
using namespace std;

ifstream fin(IN);
ofstream fout(OUT);

int h[DMAX];
int pos[DMAX], npos;
int nb;
int n;

void insert(int);
void merge(int);

int main(){
	fin >>nb;

	int i, type, x, j;
	for (i = 0; i < nb; ++i){
		fin >>type;
		if (type == 1){
			//insert
			fin >>x;
			insert(x);
		}
		else if (type == 2){
			fin >>x;
			for (j = 1; j <= n; ++j){
				if (pos[j] == x){
					//sterg
					h[j] = h[n];
					pos[j] = pos[n];
					--n;
					merge(j);
					break;
				}
			}
		}
		else if (type == 3){
			//min value
			fout <<h[1]<<'\n';
		}
	}

	fout.close();
}

void merge(int i){
	int inf = h[i];
	int father = i;
	int son = 2*i;
	int final = pos[i];

	while (son <= n){
		if (son+1 <= n && h[son] > h[son+1])
			++son;

		if (h[son] < inf){
			h[father] = h[son];
			pos[father] = pos[son];
			father = son;
			son *=2;
		}
		else break;
	}
	h[father] = inf;
	pos[father] = final;
}

void insert(int inf){
	int son = ++n;

	while (son/2 > 0 && h[son/2] > inf){
		h[son] = h[son/2];
		pos[son] = pos[son/2];
		son /= 2;
	}
	// fout <<son<<' ';
	h[son] = inf;
	pos[son] = ++npos;
}