Pagini recente » Cod sursa (job #1531995) | Cod sursa (job #2686765) | Cod sursa (job #2968506) | Cod sursa (job #2673347) | Cod sursa (job #348372)
Cod sursa(job #348372)
#include <vector>
#include <fstream>
#include <iostream>
std::vector<int> heap;
std::vector<int> v;
std::vector<int> pos;
int parent(int n){
return n/2;
}
int first(int n){
return 2*n;
}
int second(int n){
return 2*n+1;
}
bool comp(int f,int s){
return v[heap[f]]<v[heap[s]];
}
void swap(int f,int s){
std::swap(heap[f],heap[s]);
pos[heap[f]]=f;
pos[heap[s]]=s;
}
void insert(int k){
int n=heap.size();
v.push_back(k);
heap.push_back(pos.size());
pos.push_back(n);
while(parent(n)&&comp(n,parent(n))) swap(n,parent(n));
}
int max(){
return v[heap[1]];
}
void del(int k){
int n=pos[k];
swap(n,heap.size()-1);
heap.pop_back();
while(parent(n)&&comp(n,parent(n))) swap(n,parent(n));
bool go=true;
while(go){
int t=n;
go=false;
if(first(n)<heap.size()&&comp(first(n),t)){ t=first(n);go=true;}
if(second(n)<heap.size()&&comp(second(n),t)) {t=second(n);go=true;}
swap(n,t);
n=t;
}
}
int main(){
std::ifstream in("heapuri.in");
std::ofstream out("heapuri.out");
int n;in>>n;
heap.push_back(0);heap.reserve(n+1);
v.push_back(0);v.reserve(n+1);
pos.push_back(0);pos.reserve(n+1);
for(int i=0;i<n;++i){
int c;in>>c;
switch(c){
case 1:{
int x;in>>x;insert(x);break;
}
case 2:{
int x;in>>x;del(x);break;
}
case 3:{
out<<max()<<"\n";break;
}
}
}
}