Cod sursa(job #2754747)

Utilizator Radu_FilipescuFilipescu Radu Radu_Filipescu Data 26 mai 2021 14:43:30
Problema Heapuri cu reuniune Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.53 kb
#include <iostream>
#include <fstream>

using namespace std;

const int NMAX = 105;
const int INF = 2000000000;

ifstream fin( "mergeheap.in" );
ofstream fout( "mergeheap.out" );

struct node{
    int key;
    node *child, *sibling;

    node( int x ) {
        key = x;
        child = sibling = NULL;
    }
};

class pairing_heap {
private:
    node *root;
    node* merge_heap( node *A, node *B ){

        if( A == NULL ){
            A = B;
            return A;
        }

        if( B == NULL ) return A;

        if( A -> key < B -> key )
            swap( A, B );

        B -> sibling = A -> child;
        A -> child = B;

        return A;
    }

    node* two_pass_merge( node *_node ){

        if( _node == NULL || _node -> sibling == NULL )
            return _node;

        node *heap_1, *heap_2, *next_pair;

        heap_1 = _node;
        heap_2 = _node -> sibling;
        next_pair = _node -> sibling -> sibling;

        heap_1 -> sibling = heap_2 -> sibling = NULL;

        return merge_heap( merge_heap( heap_1, heap_2 ), two_pass_merge( next_pair ) );
    }
public:
    pairing_heap() {
        root = NULL;
    }

    pairing_heap( int _key ){
        root = new node( _key );
    }

    pairing_heap( node* _node ) : root( _node ) {}

    int top(){
        return root -> key;
    }

    void merge_heap( pairing_heap H ){

        if( root == NULL ){
            root = H.root;
            return;
        }
        if( H.root == NULL ) return;

        if( root -> key < H.root -> key )
            swap( root, H.root );

        H.root -> sibling = root -> child;
        root -> child = H.root;
        H.root = NULL;
    }

    void push( int _key ){
        merge_heap( pairing_heap( _key ) );
    }

    void pop(){

        node* temp = root;
        root = two_pass_merge( root -> child );

        delete temp;
    }

    void heap_union( pairing_heap &H ){
        merge_heap( H );
        H.root = NULL;
    }
};

int N, M;
pairing_heap Heap[NMAX];

int main()
{
    fin >> N >> M;

    int task, a, b;

    for( int i = 1; i <= M; ++i ){
        fin >> task;

        if( task == 1 ){
            fin >> a >> b;

            Heap[a].push( b );
        }
        if( task == 2 ){
            fin >> a;

            fout << Heap[a].top() << '\n';
            Heap[a].pop();
        }
        if( task == 3 ){
            fin >> a >> b;

            Heap[a].heap_union( Heap[b] );
        }
    }

    return 0;
}