Cod sursa(job #2289783)

Utilizator DeleDelegeanu Alexandru Dele Data 25 noiembrie 2018 11:45:16
Problema Heapuri Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.04 kb
#include <iostream>
#include <fstream>
#include <vector>
std::ifstream f("heapuri.in");
std::ofstream g("heapuri.out");
#define MaxSize 200001
class MinHeap {
private:
	struct sln {
		int x;
		int pos;
	};
	int size;
	int father(int node) {
		return node / 2;
	}
	int leftSon(int node) {
		return node * 2;
	}
	int rightSon(int node) {
		return node * 2 + 1;
	}

	void sift(int k) {
		int son;
		do {
			son = 0;
			int lSon = leftSon(k);

			if (lSon <= size) {
				son = lSon;

				int rSon = rightSon(k);
				if (rSon <= size && h[rSon].x < h[lSon].x) {
					son = rSon;
				}

				if (h[son].x >= h[k].x) {
					son = 0;
				}
			}

			if (son) {
				std::swap(h[son], h[k]);
				k = son;
			}

		} while (son);
	}

	void percolate(int k) {
		sln key = h[k];

		int kFather = father(k);
		while (k > 1 && key.x < h[kFather].x) {
			h[k] = h[kFather];
			k = kFather;
			kFather = father(k);
		}

		h[k] = key;
	}

public:
	sln h[MaxSize];
	MinHeap(int size){
		this->size = size;
	}

	int getMin() {
		return h[1].x;
	}

	int getSize() {
		return this->size;
	}

	void insert(int value, int position) {
		h[++size].x = value;
		h[size].pos = position;
		percolate(size);
	}

	void remove(int position) {
		h[position] = h[size];
		--size;

		if (position > 1 && h[position].x < h[father(position)].x)
			percolate(position);
		else
			sift(position);
	}
	void displayHeap() {
		for (int i = 1; i <= size; ++i) {
			std::cout << h[i].x << " " << h[i].pos << '\n';
		}
		std::cout << "\n\n";
	}
};
struct sln {
	int x;
	int pos;
};
bool exists[MaxSize];
int main() {
	MinHeap* h = new MinHeap(0);

	int n;
	f >> n;

	int op;
	int x;
	int pos = 0;

	for (int i = 1; i <= n; ++i) {
		f >> op;

		if (op == 1) {
			f >> x;
			++pos;
			h->insert(x, pos);
			continue;
		}

		if (op == 2) {
			f >> x;
			exists[x] = true;
			continue;
		}

		while (h->getSize() && exists[h->h[1].pos])
			h->remove(1);
		g << h->h[1].x << '\n';

	}

	return 0;
}