Pagini recente » Cod sursa (job #406703) | Cod sursa (job #1055227) | Cod sursa (job #21022) | Cod sursa (job #1922720) | Cod sursa (job #967237)
Cod sursa(job #967237)
#include<stdio.h>
#include<algorithm>
#include<iostream>
using namespace std;
#define MAX_SIZE 200010
template <typename T>
class Heap {
public:
Heap();
void pushDown(int);
void pushUp(int);
T peek();
void insert(T);
int left(int);
int right(int);
void remove(int);
private:
int heap[MAX_SIZE],position[MAX_SIZE], order[MAX_SIZE];
int size_h, size_p;
};
template<typename T>
Heap<T>::Heap() {
size_h = 0;
size_p = 0;
}
template <typename T>
int Heap<T>::left(int poz)
{
if(2 * poz > size_h)
return -1;
return 2 * poz;
}
template <typename T>
int Heap<T>::right(int poz)
{
if(2 * poz + 1 > size_h)
return -1;
return 2 * poz + 1;
}
template <typename T>
void Heap<T>::insert(T val) {
size_h++;
size_p++;
order[size_p] = val;
heap[size_h] = size_p;
position[size_p] = size_h;
pushUp(size_h);
}
template <typename T>
void Heap<T>::pushUp(int poz) {
int fp = poz / 2;
while(order[heap[poz]] < order[heap[fp]]) {
swap(heap[poz], heap[fp]);
position[heap[poz]] = poz;
position[heap[fp]] = fp;
poz = fp;
fp = poz / 2;
}
}
template <typename T>
void Heap<T>::pushDown(int poz) {
int son = left(poz);
if ( (son > 0) && (right(poz) > 0) && (order[heap[son]]> order[heap[right(poz)]]) ) {
son = right(poz);
}
if(son > 0 && (order[heap[son]] < order[heap[poz]])) {
swap(heap[poz], heap[son]);
position[heap[son]] = son;
position[heap[poz]] = poz;
pushDown(son);
}
}
template <typename T>
T Heap<T>::peek() {
return order[heap[1]];
}
template <typename T>
void Heap<T>::remove(int nr) {
order[nr] = -1;
pushUp(position[nr]);
position[heap[1]] = 0;
heap[1] = heap[size_h--];
position[heap[1]] = 1;
if(size_h > 1)
pushDown(1);
}
Heap<int> h;
int main() {
int n, cod, x;
freopen("heapuri.in","r",stdin);
freopen("heapuri.out","w", stdout);
scanf("%d", &n);
for(int i = 0; i < n; i++) {
scanf("%d",&cod);
if(cod == 1) {
scanf("%d", &x);
h.insert(x);
}
if(cod == 2) {
scanf("%d", &x);
h.remove(x);
}
if(cod == 3) {
printf("%d\n",h.peek());
}
}
return 0;
}