Cod sursa(job #2689729)

Utilizator CozehNita Horia Teodor Cozeh Data 21 decembrie 2020 22:54:47
Problema Heapuri Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.58 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;

int amount_of_numbers = 1;
int k = 1; // index of heap
ll heap[200015];
int positions[200015]; // positions[i] - the position in the heap for the ith entered number;
int posinheap[200015]; // posinheap[i] - the number of entrance in the ith position in the heap;

void insert(int number){
	heap[k] = number;
	posinheap[k] = amount_of_numbers;
	positions[amount_of_numbers] = k;
	int index = k;
	while(index != 1){
		if(heap[index/2] > heap[index]){
			swap(heap[index/2],heap[index]);
			swap(positions[amount_of_numbers], positions[posinheap[index/2]]); 
			swap(posinheap[index/2], posinheap[index]);
			index /= 2;
		} else{
			break;
		}
	}
	k++;
	amount_of_numbers++;
}

int get_min(){
	return heap[1];
}

void pop_position(int position){
	int index = positions[position];
	k--;
	heap[positions[position]] = heap[k];
	heap[k] = 0;
	swap(positions[position], positions[posinheap[k]]);
	swap(posinheap[k], posinheap[positions[posinheap[k]]]);
	position = index;
	/*
	while(position != 1) {
		if(heap[position/2] > heap[position]) {
			swap(heap[position/2], heap[position]);
			swap(positions[posinheap[position]], positions[posinheap[position/2]]);
			swap(posinheap[position/2], posinheap[position]);
			position /= 2;
		} else {
			break;
		}
	}
	*/
	while(position < k) {
		if(heap[position*2] > heap[position*2+1] && position*2+1 < k) {
			if(heap[position] > heap[position*2+1]) {
				swap(heap[position], heap[position*2+1]);
				swap(positions[posinheap[position]], positions[posinheap[position*2+1]]);
				swap(posinheap[position*2+1], posinheap[position]);
				position = position*2+1;
			} else {
				break;
			}
		} else {
			if(heap[position] > heap[position*2] && position*2 < k) {
				swap(heap[position], heap[position*2]);
				swap(positions[posinheap[position]], positions[posinheap[position*2]]);
				swap(posinheap[position*2], posinheap[position]);
				position = position*2;
			} else {
				break;
			}
		}
	}
}

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


int main(){
	int n;
	ll i,op,arg;
	fin>>n;
	for(i = 0; i < n; i++){
		fin>>op;
		if (op<3){
			fin>>arg;
			if(op == 1){
				insert(arg);
			} else {
				pop_position(arg);
			}
		} else {
			fout<<get_min()<<"\n";
		}
		/*
		for(int j = 1; j < amount_of_numbers; j++) {
			fout<<positions[j];
		}
		fout<<"\n";
		for(int j = 1; j < k; j++) {
			fout<<heap[j];
		}
		fout<<"\n";
		for(int j = 1; j < k; j++) {
			fout<<posinheap[j];
		}
		fout<<"\n";
		*/
	}
}