Cod sursa(job #2073392)

Utilizator trifangrobertRobert Trifan trifangrobert Data 23 noiembrie 2017 01:12:25
Problema Heapuri Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.25 kb
//#include <iostream>
//#include <conio.h>

#include <fstream>
#include <algorithm>
#define DIM 200010
#define INF 2000000000

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int n;
int heap[DIM]; // heap[x] inseamna valoarea aflata in nodul x din heap
int poz[DIM]; // poz[x] inseamna pozitia din heap(adica nodul din heap) unde se afla a x-a valoare adaugata in ordine cronologica
int invPoz[DIM]; // invPoz[x] inseamna al catalea element in ordine cronologica este cel de la pozitia x din heap
int nheap = 0;
int insertIndex = 0;

inline int LeftSon(const int &x)
{
	return 2 * x;
}

inline int RightSon(const int &x)
{
	return 2 * x + 1;
}

inline int Father(const int &x)
{
	return x / 2;
}

void UpHeap(int x)
{
	while (x > 1 && heap[Father(x)] > heap[x])
	{
		int xOrder = invPoz[x];
		int xFatherOrder = invPoz[Father(x)];
		swap(poz[xOrder], poz[xFatherOrder]);
		swap(invPoz[x], invPoz[Father(x)]);
		swap(heap[Father(x)], heap[x]);
		x = Father(x);
	}
}

void DownHeap(int x)
{
	while (true)
	{
		int sonMin = -1;
		if (LeftSon(x) <= nheap)
		{
			sonMin = LeftSon(x);
		}
		if (RightSon(x) <= nheap && heap[RightSon(x)] < heap[LeftSon(x)])
		{
			sonMin = RightSon(x);
		}
		if (sonMin == -1) 
		{
			break;
		}
		if (heap[sonMin] < heap[x])
		{
			int xOrder = invPoz[x];
			int xSonOrder = invPoz[sonMin];
			swap(poz[xOrder], poz[xSonOrder]);
			swap(invPoz[x], invPoz[sonMin]);
			swap(heap[x], heap[sonMin]);
			x = sonMin;
		}
		else
		{
			break;
		}
	}
}

inline void InsertInHeap(int x)
{
	heap[++nheap] = x;
	++insertIndex;
	poz[insertIndex] = nheap;
	invPoz[nheap] = insertIndex;
	UpHeap(nheap);    
}

inline void DeleteFromHeap(int x)
{
	heap[x] = heap[nheap];
	poz[invPoz[nheap]] = x;
	invPoz[x] = invPoz[nheap];
	--nheap;
	UpHeap(x);
	DownHeap(x);
}

inline int Query()
{
	return heap[1];
}

int main()
{
	fin >> n;
	int op, x;
	for (int i = 1;i <= n;++i)
	{
		fin >> op;
		switch (op)
		{
		case 1:
			fin >> x;
			InsertInHeap(x);
			break;
		case 2:
			fin >> x;
			DeleteFromHeap(poz[x]);
			break;
		case 3:
			fout << Query() << "\n";
			break;
		}
	}
	fin.close();
	fout.close();
	//_getch();
	return 0;
}