Cod sursa(job #2900623)

Utilizator disinfoion ion disinfo Data 11 mai 2022 16:43:11
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.81 kb
#include <fstream>
#include <iostream>
#include <cstring>
#define MAX 100006
using namespace std;

int heap[MAX];
int lookup[MAX];
int size = 0;
int count_inserts;
int val[MAX];

void debug(){
	for(int j=1; j<=size; ++j)
		cout << val[heap[j]] << " ";
	cout << endl;
	cout << "lookup: "  << endl;
	for(int j=1; j<=count_inserts; ++j)
		cout << j << ":" << lookup[j] << " ";
	cout << endl << endl;
}

void heapify(int idx){
	if(idx > 1 && val[heap[idx]] > val[heap[idx/2]]){
		swap(heap[idx], heap[idx/2]);
		swap(lookup[heap[idx]], lookup[heap[idx/2]]);
		heapify(idx/2);
	}
	else if(val[heap[idx]] < val[heap[2*idx]] || val[heap[idx]] < val[heap[2*idx + 1]]){
		if(val[heap[2*idx]] < val[heap[2*idx + 1]]){
			swap(heap[idx], heap[2*idx + 1]);
			swap(lookup[heap[idx]], lookup[heap[2*idx + 1]]);
			heapify(2*idx + 1);
		}
		else if(val[heap[2*idx + 1]] < val[heap[2*idx]]){
			swap(heap[idx], heap[2*idx]);
			swap(lookup[heap[idx]], lookup[heap[2*idx]]);
			heapify(2*idx);
		}
	}
}


// children of heap[i] are heap[2*i] and heap[2*i + 1]. heap[1] holds the root
void insert(int key){
	++size;
	heap[size] = key;
	lookup[key] = size;
	heapify(size);
}

void remove(int idx){
	int where = lookup[idx];
	val[idx] = -100;
	swap(heap[where], heap[size]);
	swap(lookup[heap[where]], lookup[heap[size]]);
	--size;
	heapify(where);
}



int main(){
	ifstream fin;
	ofstream fout;
	fin.open("heapuri.in");
	fout.open("heapuri.out"); 
	int m, n, q, x, idx;
	val[0] = -100;

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

		fin >> q;

		if(q == 1){
			++count_inserts;
			idx = count_inserts;
			fin >> x;
			val[idx] = -x;
			insert(idx);
			
		}
		else if(q == 2){
			fin >> idx;
			remove(idx);
		}
		else if(q == 3){
			fout << - val[heap[1]] << "\n";
		}
	
	}

	

}