Cod sursa(job #1986710)

Utilizator gabriel.bjgGabriel b. gabriel.bjg Data 28 mai 2017 20:24:25
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.56 kb
//#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <algorithm>
#include <functional>
#include <queue>
#include <unordered_map>

using namespace std;

ifstream fin("heapuri.in");
ofstream fout("heapuri.out");

#define NR 200005

int heap[NR], heapLen;
unordered_map<int, int> pos;
vector <int> nth;

void heapify(int p)
{
	bool left = true, right = true;
	int q = -1;

	while (p > 1 && heap[p] < heap[p / 2])
	{
		swap(pos[heap[p]], pos[heap[p / 2]]);
		swap(heap[p], heap[p / 2]);
		p /= 2;
	}

	while (left || right)
	{
		left = false;
		right = false;
		q = -1;
		if (p * 2 <= heapLen && heap[p] > heap[p * 2])
			left = true;
		if (p * 2 + 1 <= heapLen && heap[p] > heap[p * 2 + 1])
			right = true;

		if (left && right)
		{
			q = (heap[p * 2] < heap[p * 2 + 1]) ? (p * 2) : (p * 2 + 1);
		}
		else if (left)
		{
			q = p * 2;
		}

		if (q != -1)
		{
			swap(pos[heap[p]], pos[heap[q]]);
			swap(heap[p], heap[q]);
		}
		p *= 2;
	}
}

void addHeap(int x)
{
	heap[++heapLen] = x;
	pos[x] = heapLen;
	nth.push_back(x);
	heapify(heapLen);
}

void removeHeap(int xth)
{
	int p = pos[nth[xth - 1]];
	swap(pos[heap[p]], pos[heap[heapLen]]);
	swap(heap[p], heap[heapLen]);
	heapLen--;
	heapify(p);
}

int main()
{
	int n, i, op, x;

	fin >> n;
	for (i = 0; i < n; ++i)
	{
		fin >> op;
		switch (op)
		{
			case 1:
				fin >> x;
				addHeap(x);
				break;
			case 2:
				fin >> x;
				removeHeap(x);
				break;
			case 3:
				fout << heap[1] << "\n";
				break;
		}
	}

	return 0;
}