Pagini recente » Cod sursa (job #1841187) | Cod sursa (job #1638461) | Cod sursa (job #1061377) | Cod sursa (job #2431457) | Cod sursa (job #965154)
Cod sursa(job #965154)
#include<stdio.h>
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
template <typename T>
struct el {
T val;
int ind;
el(T v, int i) {
val = v;
ind = i;
}
};
template <typename T>
class Heap {
public:
Heap();
void pushDown(int);
void pushUp(int);
T pop();
T peek();
void insert(T);
int left(int);
int right(int);
void show();
void sort();
void remove(int);
void rem_nth_el(int);
private:
vector<el<T> > heap;
vector<int> position;
int size, pos_ind;
};
template<typename T>
Heap<T>::Heap() {
size = 0;
pos_ind = 0;
}
template <typename T>
int Heap<T>::left(int poz)
{
if(2 * poz + 1 > size)
return -1;
return 2 * poz + 1;
}
template <typename T>
int Heap<T>::right(int poz)
{
if(2 * poz + 2 > size)
return -1;
return 2 * poz + 2;
}
template <typename T>
void Heap<T>::insert(T val) {
el<T> new_el(val,size);
heap.push_back(new_el);
position.push_back(pos_ind);
pushUp(size);
size++;
pos_ind++;
}
template <typename T>
void Heap<T>::pushUp(int poz) {
int fp = (poz - 1)/2;
while(heap[poz].val < heap[fp].val) {
swap(heap[poz], heap[fp]);
swap(position[heap[poz].ind], position[heap[fp].ind]);
poz = fp;
fp = (poz - 1)/2;
}
}
template <typename T>
void Heap<T>::pushDown(int poz) {
int son = left(poz);
if ( (son > 0) && (right(poz) > 0) && (heap[son].val > heap[right(poz)].val) ) {
son = right(poz);
}
if(son > 0 && (heap[son].val < heap[poz].val)) {
swap(heap[poz], heap[son]);
swap(position[heap[poz].ind], position[heap[son].ind]);
pushDown(son);
}
}
template <typename T>
T Heap<T>::peek() {
return heap[0].val;
}
template <typename T>
T Heap<T>::pop() {
T save = heap[0].val;
heap[0] = heap[size - 1];
size--;
pushDown(0);
return save;
}
template <typename T>
void Heap<T>::remove(int poz) {
//swap(heap[poz], heap[size-1]); swap(size,position[nr])
heap[poz] = heap[size-1];
swap(position[heap[position[poz-1]].ind], position[heap[size - 1].ind]);
heap.pop_back();
size--;
pushDown(poz);
}
template <typename T>
void Heap<T>::rem_nth_el(int nr) {
remove(position[nr-1]);
}
template <typename T>
void Heap<T>::sort() {
int dim = size;
for(int i = 0; i < dim; i++)
cout<<pop()<<" ";
cout<<"\n";
}
template<typename T>
void Heap<T>::show() {
for(int i = 0; i < size; i++)
cout<<heap[i].val<<" ";
cout<<"\n";
for(int i = 0; i < pos_ind; i++)
cout<<position[i]<<" ";
cout<<"\n";
}
int main() {
Heap<int> h;
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.rem_nth_el(x);
//h.remove(x);
}
if(cod == 3) {
printf("%d\n",h.peek());
}
}
/*cout<<"aici show--";h.show();
h.rem_nth_el(2);
cout<<"aici show--";h.show();
h.rem_nth_el(4);
cout<<"aici show--";h.show();*/
return 0;
}