Cod sursa(job #2174936)

Utilizator adriangh3Adrian Gheorghiu adriangh3 Data 16 martie 2018 14:19:18
Problema Heapuri Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <vector>
using namespace std;
ifstream in("heapuri.in");
ofstream out("heapuri.out");
int *H = new int[200010], l, nr, *v=new int[200010], *pos=new int[200010];

inline int Father(int nod)
{
	return nod / 2;
}

inline int left_son(int nod)
{
	return nod * 2;
}

inline int right_son(int nod)
{
	return nod * 2 + 1;
}

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

void sift(int nod)
{
	int son;
	while (left_son(nod) <= l)
	{
		son = -1;
		if(v[H[left_son(nod)]]<v[H[nod]]) son = left_son(nod);
		if (right_son(nod) <= l && v[H[right_son(nod)]]<v[H[left_son(nod)]]) son = right_son(nod);
		if (son == -1) break;
		swap(H[nod], H[son]);
		swap(pos[H[nod]], pos[H[son]]);
		nod = son;
	}
}

void percolate(int nod)
{
	int father;
	while (nod != 1)
	{
		father = Father(nod);
		if (v[H[father]] > v[H[nod]])
		{
			swap(H[father], H[nod]);
			swap(pos[H[father]], pos[H[nod]]);
			nod = father;
		}
		else break;
	}
}

int main()
{
	int n, op, x;
	in >> n;
	for (int i = 0; i<n; i++)
	{
		in >> op;
		if (op == 1)
		{
			in >> x;
			v[++nr] = x;
			H[++l] = nr;
			pos[nr] = l;
			percolate(l);
		}
		else if (op == 2)
		{
			in >> x;
			H[pos[x]] = H[l];
			H[l--] = 0;
			if (pos[x]!=1&&v[H[Father(pos[x])]] > v[H[pos[x]]]) percolate(pos[x]);
			else sift(pos[x]);
		}
		else
		{
			out << v[H[1]] << '\n';
		}
	}
	return 0;
}