Cod sursa(job #2908218)

Utilizator NicuDirvaDirva Nicolae NicuDirva Data 2 iunie 2022 09:53:58
Problema Heapuri cu reuniune Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.47 kb
#include <iostream>
#include <fstream>

using namespace std;

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

struct node{
    int key;
    node *left_child, *next_sibling;

    node( int x ):key(x), left_child(NULL), next_sibling(NULL){}
};

class pairing_heap{

    node *root;

    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 -> next_sibling = H1 -> left_child;
        H1 -> left_child = H2;

        return H1;
    }

    node* two_pass_merge( node *_node ){

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

        node *heap_1, *heap_2, *next_pair;

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

        heap_1 -> next_sibling = heap_2 -> next_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 -> next_sibling = root -> left_child;
        root -> left_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 -> left_child );

        delete temp;
    }

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

pairing_heap heap[101];
int N, M;

int main()
{
int op, m, x, m_s;
fin>>N>>M;
for(int i=0;i<M;i++)
{
    fin>>op;

    if(op==1)
    {
        fin>>m>>x;
        heap[m].push(x);
    }

    if(op==2)
    {
        fin>>m;
        fout<<heap[m].top()<<"\n";
        heap[m].pop();
    }

    if(op==3)
    {
        fin>>m>>m_s;
        heap[m].heap_union(heap[m_s]);

    }
}

fin.close();
fout.close();


return 0;

}