Pagini recente » Cod sursa (job #987111) | Cod sursa (job #434906) | Cod sursa (job #2323550) | Cod sursa (job #1257774) | Cod sursa (job #2907059)
#include <iostream>
#include <fstream>
using namespace std;
ifstream fin("mergeheap.in");
ofstream fout("mergeheap.out");
const int maxim = 101;
struct node{
int key;
node *copil, *frate;
node( int x ) : key( x ), copil( NULL ), frate( NULL ) {}
};
class pairing_heap{
node *rad;
node* merge_heap( node* H1, node* H2 ){
if( H1 == NULL ){
H1 = H2;
return H1;
}
if( H2 == NULL ) return H1;
if( H1 -> key < H2 -> key )
swap( H1, H2 );
H2 -> frate = H1 -> copil;
H1 -> copil = H2;
return H1;
}
node* two_pass_merge( node *_node ){
if( _node == NULL || _node -> frate == NULL )
return _node;
node *heap_1, *heap_2, *next_pair;
heap_1 = _node;
heap_2 = _node -> frate;
next_pair = _node -> frate -> frate;
heap_1 -> frate = heap_2 -> frate = NULL;
return merge_heap( merge_heap( heap_1, heap_2 ), two_pass_merge( next_pair ) );
}
public:
pairing_heap() : rad( NULL ) {}
pairing_heap( int _key ){
rad = new node( _key );
}
pairing_heap( node* _node ) : rad( _node ) {}
int top(){
return rad -> key;
}
void merge_heap( pairing_heap H ){
if( rad == NULL ){
rad = H.rad;
return;
}
if( H.rad == NULL ) return;
if( rad -> key < H.rad -> key )
swap( rad, H.rad );
H.rad -> frate = rad -> copil;
rad -> copil = H.rad;
H.rad = NULL;
}
void push( int _key ){
merge_heap( pairing_heap( _key ) );
}
void pop(){
node* temp = rad;
rad = two_pass_merge( rad -> copil );
delete temp;
}
void heap_union( pairing_heap &H ){
merge_heap( H );
H.rad = NULL;
}
};
int N, Q;
pairing_heap heap[maxim];
int main()
{
int op, h, x, h1, h2;
fin >> N >> Q;
for( int i = 1; i <= Q; i++ )
{
fin >> op;
if( op == 1 ){
fin >> h >> x;
heap[h].push( x );
}
if( op == 2 ){
fin >> h;
fout << heap[h].top() << '\n';
heap[h].pop();
}
if( op == 3 ){
fin >> h1 >> h2;
heap[h1].heap_union( heap[h2] );
}
}
return 0;
}