Pagini recente » Cod sursa (job #1907011) | Cod sursa (job #2095971) | Cod sursa (job #3212091) | Cod sursa (job #2763166) | Cod sursa (job #3264424)
#include <fstream>
#include <vector>
#include <iostream>
using namespace std;
const int NMAX=2e5;
ifstream fin("heapuri.in");
ofstream fout("heapuri.out");
int heap[NMAX+1],heap_pos[NMAX+1],values[NMAX+1];
int n,heap_size;
void heap_swap(int node_1,int node_2){
swap(heap_pos[heap[node_1]],heap_pos[heap[node_2]]);
swap(heap[node_1],heap[node_2]);
}
void heap_up(int pos){
while (pos > 1 && values[heap[pos]] < values[heap[pos]] >> 1) //swapping children with father nodes (up swap)
{ //in case of newly created imbalance
heap_swap(pos, pos >> 1);
pos >>= 1;
}
}
void heap_down(int pos){
int st,dr,best;
while ((pos << 1) <= heap_size) //swapping father with children nodes in case of imbalance (down swap)
{
st = (pos << 1); //left node is default in case of one-child father node
dr = st + 1;
best = st;
if (dr <= heap_size && values[heap[st]] > values[heap[dr]])//right node is chosen in case of smaller value and availability
best = dr;
if (values[heap[pos]] > values[heap[best]])//if father > child values, swap
heap_swap(pos, best);
else
break;
pos = best;
}
}
void heap_add(int new_value){
values[++n]=new_value;
heap[++heap_size]=n;
heap_pos[n]=heap_size;
heap_up(heap_size);
}
void heap_elimination(int new_index){
int pos_index=heap_pos[new_index];
heap_swap(pos_index, heap_size); //swap the eliminated node with the last node and decrease the size
--heap_size;
heap_up(pos_index);
heap_down(pos_index);
}
int main()
{
int operations,case_type,added_value;
fin>>operations;
for(int nr_ops=1;nr_ops<=operations;nr_ops++)
{
fin>>case_type;
if(case_type!=3)
fin>>added_value;
if(case_type==1)
heap_add(added_value);
else if(case_type==2)
heap_elimination(added_value);
else
fout<<values[heap[1]]<<"\n";
/*for(int i=1;i<=heap_size;i++)
cout<<values[heap[i]]<<" ";
cout<<"\n";*/
}
return 0;
}