Cod sursa(job #2894457)

Utilizator AlexePaulAlexe Paul AlexePaul Data 27 aprilie 2022 20:46:33
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>

#define FILE "heapuri"

using namespace std;

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

pair<int,int> heap[200005];
int n,x,op,size;

void insert(int x){
	int pos = size+1;
	pair<int,int> xp = {x, size+1};
	heap[pos] = xp;
	while(pos > 0){
		if(heap[pos/2].first > heap[pos].first){
			swap(heap[pos/2],heap[pos]);
			pos /= 2;
		}
		else{
			break;
		}
	}
}

void remove(int x){
	int pos=0;
	for(int i = 1; i <= size; ++i){
		if(heap[i].second == x)
			pos = i;
	}

	//cout << heap[pos].first << " : " << heap[size].first << '\n';
	swap(heap[pos],heap[size]);
	heap[size].first = 0;
	heap[size].second = 0;

	while(heap[pos].first < heap[pos/2].first){
		if(heap[pos].first < heap[pos/2].first){
			swap(heap[pos/2],heap[pos]);
			pos /= 2;
		}
	}

	while(2*pos < size && heap[pos].first > min(heap[2*pos].first,heap[2*pos+1].first)){
		if(heap[2*pos].first < heap[2*pos+1].first || heap[2*pos+1].second == 0){
			swap(heap[2*pos], heap[pos]);
			pos *= 2;
			continue;
		}
		else if (heap[2*pos+1].second != 0){
			swap(heap[2*pos+1], heap[pos]);
			pos = 2*pos+1;
			continue;
		}
		break;
	}
}

int main(){
	fin >> n;
	for(int i = 0; i < n; ++i){
		fin >> op;
		switch (op){
			case 1:
				fin >> x;
				insert(x);
				size++;
				break;
			case 2:
				fin >> x;
				remove(x);
				size--;
				break;
			case 3:
				fout << heap[1].first << '\n';
				break;
			default:
				break;	
		}
	/*for(int i = 1; i <= size; ++i){
		cout << heap[i].first << ' ';
	}
	cout << '\n';*/		
	}
}