Cod sursa(job #2734519)

Utilizator HadircaDionisieHadirca Dionisie HadircaDionisie Data 1 aprilie 2021 00:27:40
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <fstream>
#include <vector>

#include <algorithm>

using namespace std;

int h[200010], poz[200010],nums[200010],n, hSize ,numsSize ;

int getParent(int i) {
	return (i - 1 )/ 2;
}

int rightSon(int i) {
	return 2 * i + 2;
}

int leftSon(int i) {
	return 2 * i + 1;
}


void insert(int num) {
	int x = hSize;

	poz[num] = numsSize;
	nums[numsSize++] = num;
	h[hSize++] = num;
	
	while (x > 0 && h[getParent(x)] > h[x]) {
		swap(h[x], h[getParent(x)]);
		poz[h[x]] = x;
		poz[h[(x - 1) / 2]] = (x - 1) / 2;
		x = (x - 1) / 2;
	}
}

void deleteAtIndex(int idx) {
	hSize--;
	h[idx] = h[hSize];
	poz[h[hSize]] = idx;
	while (idx < hSize - 1) {
		if (h[idx] >= h[leftSon(idx)] && h[idx] >= h[rightSon(idx)]){
			if (h[leftSon(idx)] <= h[rightSon(idx)]) {
				swap(h[idx], h[leftSon(idx)]);
				idx = 2 * idx + 1;
			}
			else if (2 * idx + 2 < hSize) {
				swap(h[idx], h[rightSon(idx)]);
				idx = 2 * idx + 2;
			}
			else {
				swap(h[idx], h[leftSon(idx)]);
				idx = 2 * idx + 1;
			}
		}
	}
}

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

int main() {
	
	fin >> n;

	for (int i = 0; i < n; i++) {
		int operatie;
		int numar;

		fin >> operatie;
		if (operatie == 1) {
			fin >> numar;
			insert(numar);
		}

		else if (operatie == 2) {
			fin >> numar;
			deleteAtIndex(poz[nums[numar - 1]]);
		}
		else if (operatie == 3) {
			fout << h[0] << '\n';
		}
	}
}