Pagini recente » Cod sursa (job #2821509) | Cod sursa (job #2257809) | Cod sursa (job #3274797) | Cod sursa (job #1896815) | Cod sursa (job #2626290)
#include <fstream>
#include <iostream>
using namespace std;
ifstream in ("heapuri.in");
ofstream out ("heapuri.out");
int heap[200001],order[200001],posi[200001],turn = 0 ;
int parent(int x){return x/2;}
int left_child(int x){return x*2;}
int right_child(int x){return x*2+1;}
void sift(int *arr, int n, int k){
int child = 1;
while(child){
child = 0;
if(right_child(k) <= n)
{
if(arr[ right_child(k) ] < arr[ left_child(k) ])
child = right_child(k);
else
child = left_child(k);
}
else if(left_child(k) <= n)
{
child = left_child(k);
}
if(arr[k] < arr[ child ])
child = 0;
if( child != 0 )
{
posi[arr[child]]=parent(child);
int temp = arr[k];
arr[k] = arr[child];
arr[child] = temp;
k = child;
}
}
posi[arr[k]]=k;
}
void percolate(int *arr, int n, int k){
int key = arr[k];
while (k > 1 && key < arr[parent(k)])
{
arr[k] = arr[ parent(k) ];
posi[arr[k]]=k;
k = parent(k);
}
arr[k] = key;
posi[key]=k;
}
void erase(int *arr, int &n, int k)
{
k=order[k];
int poz=posi[k];
// for(int i = 1 ; i <= n; i++)
// if( k == arr[i])
// {
// poz = i;
// break;
// }
posi[k]=0;
arr[poz] = arr[n];
n--;
if(k > 1 && arr[poz] < arr[ parent(poz) ])
percolate(arr, n, poz);
else
sift(arr, n, poz);
}
void add(int *arr, int &n, int k)
{
n++;
posi[k]=n;
order[++turn]=k;
arr[n] = k;
percolate (arr, n, n);
}
int main()
{
int n, length = 0;
in >> n;
for(int i = 0 ; i < n ; i++)
{
int op,x;
in >> op;
if(op==1)
{
in >> x;
add(heap, length, x);
}
if(op==2)
{
in >> x;
erase(heap, length, x);
}
if(op==3)
{
out << heap[1] << '\n';
}
}
return 0;
}