Pagini recente » Cod sursa (job #1396657) | Cod sursa (job #2763834) | Cod sursa (job #2560300) | Cod sursa (job #1530681) | Cod sursa (job #650980)
Cod sursa(job #650980)
#include <vector>
#include <iostream>
#include <cstdio>
using namespace std;
class heap
{
private:
vector<int> list;
vector<int> order;
vector<int> location;
void swap(int& a, int &b);
public:
int top();
void add(int n);
void del(int d_elm);
};
void heap::swap(int& a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}
int heap::top()
{
return order[ list[0] ];
}
void heap::add(int n)
{
order.push_back(n);
location.push_back( order.size()-1 );
list.push_back( order.size()-1 );
int p_cur = list.size()-1;
int p_par = p_cur/2;
while ( p_cur )
{
if ( order[ list[p_par] ] > order[ list[p_cur] ] )
{
swap( list[p_par], list[p_cur] );
location[ list[p_par] ] = p_par;
location[ list[p_cur] ] = p_cur;
}
p_cur = p_par;
p_par = ( p_cur ) ? p_cur/2 : -1;
}
}
void heap::del(int d_elm)
{
int p_cur = location[ d_elm-1 ];
list[ p_cur ] = list[ list.size()-1 ];
location[ list[ p_cur ] ] = p_cur;
location[ d_elm-1 ] = -1;
list.pop_back();
int p_ch1 = 2*p_cur+1;
int p_ch2 = 2*p_cur+2;
while ( p_ch1 <= list.size()-1 || p_ch2 <= list.size()-1 )
{
if ( p_ch1 <= list.size()-1 && p_ch2 <= list.size()-1 )
{
if ( order[ list[p_ch1] ] < order[ list[p_cur] ] && order[ list[p_ch1] ] <= order[ list[p_ch2] ] )
{
swap( list[p_ch1], list[p_cur] );
location[ list[p_ch1] ] = p_ch1;
location[ list[p_cur] ] = p_cur;
p_cur = p_ch1;
}
else if ( order[ list[p_ch2] ] < order[ list[p_cur] ] && order[ list[p_ch2] ] < order[ list[p_ch1] ] )
{
swap( list[p_ch2], list[p_cur] );
location[ list[p_ch2] ] = p_ch2;
location[ list[p_cur] ] = p_cur;
p_cur = p_ch2;
}
else
break;
}
else if ( p_ch1 <= list.size()-1 )
{
if ( order[ list[p_ch1] ] < order[ list[p_cur] ] )
{
swap( list[p_ch1], list[p_cur] );
location[ list[p_ch1] ] = p_ch1;
location[ list[p_cur] ] = p_cur;
p_cur = p_ch1;
}
else
break;
}
else if ( p_ch1 <= list.size()-1 )
{
if ( order[ list[p_ch2] ] < order[ list[p_cur] ] )
{
swap( list[p_ch2], list[p_cur] );
location[ list[p_ch2] ] = p_ch2;
location[ list[p_cur] ] = p_cur;
p_cur = p_ch2;
}
else
break;
}
p_ch1 = 2*p_cur+1;
p_ch2 = 2*p_cur+2;
}
}
int main()
{
int n, cmd, t;
heap my_heap;
freopen("heapuri.in", "r", stdin);
freopen("heapuri.out", "w", stdout);
scanf("%d", &n);
for (int i=0; i<n; i++)
{
scanf("%d", &cmd);
switch (cmd)
{
case 1:
scanf("%d", &t);
my_heap.add(t);
break;
case 2:
scanf("%d", &t);
my_heap.del(t);
break;
case 3:
printf("%d\n", my_heap.top() );
break;
}
}
}