Cod sursa(job #2703880)

Utilizator ssenseEsanu Mihai ssense Data 9 februarie 2021 13:39:34
Problema Heapuri Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.59 kb
#include <bits/stdc++.h>
#define startt ios_base::sync_with_stdio(false);cin.tie(0);
#pragma GCC target ("avx2")
#pragma GCC optimization ("O3")
#pragma GCC optimization ("unroll-loops")
typedef unsigned long long ull;
typedef long long  ll;
using namespace std;
#define FOR(n) for(int i=0;i<n;i++)
#define vt vector
#define vint vector<int>
#define all(v) v.begin(), v.end()
#define MOD 1000000007
#define MOD2 998244353
#define MX 1000000000
#define nax 100005
#define MXL 1000000000000000000
#define PI 3.14159265
#define pb push_back
#define pf push_front
#define sc second
#define fr first
#define int ll
#define endl '\n'
#define ld long double

struct bheap
{
	vector<pair<int, int>> heap;
	vector<int> pos;
	int minimum()
	{
		return heap[0].fr;
	}
	void insert(int x)
	{
		heap.pb({x, pos.size()});
		pos.pb(heap.size()-1);
		while(heap[(pos.back()-1)/2].fr > heap[pos.back()].fr && pos.back() != 0)
		{
			pos[heap[(pos.back()-1)/2].sc] = pos.back();
			swap(heap[(pos.back()-1)/2], heap[pos.back()]);
			pos.back() = (pos.back()-1)/2;
		}
	}
	void remove_xth(int x)
	{
		x--;
		swap(heap.back(), heap[pos[x]]);
		pos[heap[pos[x]].sc] = pos[x];
		heap.pop_back();
		int nowp = pos[x];
		if(heap[(nowp-1)/2] > heap[nowp])
		{
			while(heap[(nowp-1)/2] > heap[nowp] && nowp != 0)
			{
				pos[heap[(nowp-1)/2].sc] = nowp;
				pos[heap[nowp].sc] = (nowp-1)/2;
				swap(heap[(nowp-1)/2], heap[nowp]);
				nowp = (nowp-1)/2;
			}
		}
		if((heap.size() > nowp*2+1 && heap[nowp] > heap[nowp*2 + 1]) || (heap.size() > nowp*2+2 && heap[nowp] > heap[nowp*2 + 2]))
		{
			while((heap.size() > nowp*2+1 && heap[nowp] > heap[nowp*2 + 1]) || (heap.size() > nowp*2+2 && heap[nowp] > heap[nowp*2 + 2]))
			{
				if(heap.size() >= nowp*2+2)
				{
					pos[heap[nowp].sc] = nowp*2+1;
					pos[heap[nowp*2 + 1].sc] = nowp;
					swap(heap[nowp], heap[nowp*2+1]);
					nowp = nowp*2+1;
				}
				else
				{
					if(heap[nowp*2+1] < heap[nowp*2+2])
					{
						pos[heap[nowp].sc] = nowp*2+1;
						pos[heap[nowp*2 + 1].sc] = nowp;
						swap(heap[nowp], heap[nowp*2+1]);
						nowp = nowp*2+1;
					}
					else
					{
						pos[heap[nowp].sc] = nowp*2+2;
						pos[heap[nowp*2 + 2].sc] = nowp;
						swap(heap[nowp], heap[nowp*2+2]);
						nowp = nowp*2+2;
					}
				}
			}
		}
	}
};

int32_t main(){
	startt;
	freopen("heapuri.in", "r", stdin);
	freopen("heapuri.out", "w", stdout);
	bheap heap;
	int n;
	cin >> n;
	for(int i = 0; i < n; i++)
	{
		int c;
		cin >> c;
		if(c == 3)
		{
			cout << heap.minimum() << endl;
		}
		if(c == 2)
		{
			int x;
			cin >> x;
			heap.remove_xth(x);
		}
		if(c == 1)
		{
			int x;
			cin >> x;
			heap.insert(x);
		}
	}
}