Cod sursa(job #3179322)

Utilizator EduardSubreduSubredu Eduard EduardSubredu Data 3 decembrie 2023 15:03:41
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.55 kb
#pragma warning(disable : 4996)
#include <iostream>
#include <fstream>
#define numar_mare 1000003 
using namespace std;

ifstream f("heapuri.in");
ofstream g("heapuri.out");

int father(int k)
{
	return k / 2;
}
int left_son(int k)
{
	return k * 2;
}
int right_son(int k)
{
	return k * 2 + 1;
}

void sift(int heap[], int n, int k)
{
	int son;
	do {
		son = 0;
		if (left_son(k) <= n) {
			son = left_son(k);
			if (right_son(k) <= n && heap[son] > heap[right_son(k)])
			{
				son = right_son(k);
			}
			if (heap[son] < heap[k]) {
				swap(heap[k], heap[son]);
				k = son;
			}
			else son = 0;
		}
	} while (son);
}

void percolate(int heap[], int n, int k) {
	while (k > 1 && heap[k] < heap[father(k)])
	{
		swap(heap[k], heap[father(k)]);
		k = father(k);
	}
}

void insert(int heap[], int& n, int x) {
	n++;
	heap[n] = x;
	percolate(heap, n, n);
}

void stergere(int heap[], int& n, int x) {
	swap(heap[n], heap[x]);
	n--;
	if (x > 1 && heap[x] < heap[father(x)]) {
		percolate(heap, n, x);
	}
	else {
		sift(heap, n, x);
	}
}
int nr, ordine[200001];
int main()
{
	int heap[200001], n = 0;
	int m, op, val;
	f >> m;
	for (int i = 1; i <= m; i++)
	{
		f >> op;
		if (op == 1) {
			f >> val;
			insert(heap, n, val);
			nr++;
			ordine[nr] = val;
		}
		else if (op == 2) {
			f >> val;
			for (int j = 1; j <= n; j++)
			{
				if (heap[j] == ordine[val]) {
					val = j;
					break;
				}
			}
			stergere(heap, n, val);
		}
		else {
			g << heap[1] << "\n";
		}
	}



	return 0;
}