Pagini recente » Cod sursa (job #2394387) | Cod sursa (job #2924725) | Cod sursa (job #918296) | Cod sursa (job #2469920) | Cod sursa (job #2767648)
#include <bits/stdc++.h>
using namespace std ;
bool smaller(int a,int b) {
return a < b;
}
template <typename T>
class heap {
private:
int lg = 1;
vector<int> t;
vector<int> poz;// poz[i] = unde se afla in heap cel deal i-lea intrat
vector<int> ind;// ind[i] = al catelea a intrat cel de pe poz i din heap
int parrent(int idx) {
return idx/2;
}
bool (*comp)(T a, T b);
int left_son(int idx) {
return 2 * idx;
}
int right_son(int idx) {
return 2 * idx + 1;
}
void upHeap(int idx) {
while(idx > 1 && comp(t[idx], t[parrent(idx)]) ) {
swap(t[parrent(idx)], t[idx]);
poz[ind[idx]] = parrent(idx);
poz[ind[parrent(idx)]] = idx;
swap(ind[idx], ind[parrent(idx)]);
idx = parrent(idx);
}
}
void downHeap(int idx) {
// recursiv
int best = idx;
if(left_son(idx) <= size() && comp(t[left_son(idx)], t[best]) ) {
best = left_son(idx);
}
if(right_son(idx) <= size() && comp(t[right_son(idx)],t[best] )) {
best = right_son(idx);
}
if(best != idx) {
swap(t[best], t[idx]);
poz[ind[best]] = idx;
poz[ind[idx]] = best;
swap(ind[idx], ind[best]);
downHeap(best);
}
}
public:
int size() {
return t.size() - 1;
}
heap(bool (* f)(T a, T b) ) {
t.resize(1);
poz.resize(1);
ind.resize(1);
comp = f;
}
void insert(T val) {
t.push_back(val);
poz.push_back(size());
ind.push_back(lg++);
upHeap(size());
}
void del(int x) {
t[poz[x]] = t[size()];
poz[ind[size()]] = poz[x];
ind[poz[x]] = ind[size()];
t.pop_back();
poz.pop_back();
ind.pop_back();
downHeap(poz[x]);
upHeap(poz[x]);
}
void afis() {
for(int i = 1; i <= size(); i++)
printf("%d %d %d\n",t[i],poz[i],ind[i]);
}
void top() {
printf("%d\n",t[1]);
}
};
int main() {
freopen("heapuri.in","r",stdin);
freopen("heapuri.out","w",stdout);
int t;
scanf("%d",&t);
heap<int> h(smaller);
while(t--) {
int type;
scanf("%d",&type);
if(type == 1) {
int x;
scanf("%d",&x);
h.insert(x);
}else if(type == 2) {
int x;
scanf("%d",&x);
h.del(x);
}else {
h.top();
}
}
// heap<int> h(smaller);
// h.insert(3);
// h.insert(2);
// h.insert(1);
// h.del(3);
// h.top();
// h.insert(0);
// h.afis();
// h.del(4);
// h.top();
return 0;
}