Cod sursa(job #3231077)

Utilizator pielevladutPiele Vladut Stefan pielevladut Data 24 mai 2024 16:48:50
Problema Heapuri cu reuniune Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.54 kb
#include <iostream>
#include <fstream>

using namespace std;

const int nmax = 101;
const int INF = 2000000001;

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

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

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

class pairing_heap{

    node *root;

    node* merge_heap( node* h1, node* h2 ){

        if( h1 == NULL ){
            h1 = h1;
            return h1;
        }
        if( h2 == NULL ) return h1;

        if( h1 -> key < h2 -> key )
            swap( h1, h2 );

        h2 -> sibling = h1 -> child;
        h1 -> child = h1;

        return h1;
    }

    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 h1 ){

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

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

        h1.root -> sibling = root -> child;
        root -> child = h1.root;
        h1.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, h, x, h1, h2;
    for( int i = 1; i <= m; ++i ){

        fin >> task;

        if( task == 1 ){
            fin >> h >> x;

            heap[h].push( x );
        }
        if( task == 2 ){
            fin >> h;

            fout << heap[h].top() << '\n';
            heap[h].pop();
        }
        if( task == 3 ){
            fin >> h1 >> h2;

            heap[h1].heap_union( heap[h2] );
        }
    }

    return 0;
}