Cod sursa(job #3221246)

Utilizator DobraVictorDobra Victor Ioan DobraVictor Data 6 aprilie 2024 13:16:37
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <iostream>
#include <fstream>
#include <stdint.h>
#include <limits.h>
#include <utility>

const int32_t MAX_N = 200000;

#define PARENT_IND(ind) (((ind + 1) >> 1) - 1)
#define CHILD1_IND(ind) (((ind + 1) << 1) - 1)
#define CHILD2_IND(ind) ((ind + 1) << 1)

int32_t vec[MAX_N], size = 0;
int32_t inds[MAX_N];
int32_t heap[MAX_N], heapSize;

void Insert(int32_t val) {
	vec[size] = val;
	inds[size] = heapSize;
	heap[heapSize] = size;

	for(int32_t ind = heapSize; ind && vec[heap[ind]] < vec[heap[PARENT_IND(ind)]]; ind = PARENT_IND(ind)) {
		std::swap(inds[heap[ind]], inds[heap[PARENT_IND(ind)]]);
		std::swap(heap[ind], heap[PARENT_IND(ind)]);
	}
	
	++heapSize;
	++size;
}
void Remove(int32_t val) {
	int32_t ind = inds[val];
	std::swap(heap[ind], heap[--heapSize]);

	while(ind < heapSize) {
		int32_t child1 = ((ind + 1) << 1) - 1;
		int32_t child2 = (ind + 1) << 1;

		int32_t val = vec[heap[ind]];
		int32_t val1 = (child1 < heapSize) ? vec[heap[child1]] : INT_MAX;
		int32_t val2 = (child2 < heapSize) ? vec[heap[child1]] : INT_MAX;

		int32_t nextInd = -1;
		if(val1 < val && val2 < val) {
			if(val1 < val2) {
				nextInd = child1;
			} else {
				nextInd = child2;
			}
		} else if(val1 < val) {
			nextInd = child1;
		} else if(val2 < val) {
			nextInd = child2;
		}

		if(nextInd == -1)
			break;
		
		std::swap(inds[heap[ind]], inds[heap[nextInd]]);
		std::swap(heap[ind], heap[nextInd]);
		ind = nextInd;
	}
}

int main() {
	std::ifstream fin("heapuri.in");
	std::ofstream fout("heapuri.out");

	int32_t n;
	fin >> n;

	for(int32_t i = 0; i != n; ++i) {
		int32_t c, x;
		fin >> c;

		switch(c) {
		case 1:
			fin >> x;
			Insert(x);
			break;
		case 2:
			fin >> x;
			--x;
			Remove(x);
			break;
		case 3:
			fout << vec[heap[0]] << '\n';
			break;
		}
	}

	fin.close();
	fout.close();

	return 0;
}