Cod sursa(job #3126255)

Utilizator mjmilan11Mujdar Milan mjmilan11 Data 6 mai 2023 14:09:50
Problema Heapuri cu reuniune Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.35 kb
#include <bits/stdc++.h>

using namespace std;

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

const int NMAX = 102;

struct Node{
    int val;
    int rang;
    Node* child;
    Node* sibling;
    Node(int _val){
        val = _val;
        rang = 0;
        child = nullptr;
        sibling = nullptr;
    }
};

class Rank_Pairing_Heap{
private:
    Node* root;

    Node* merge_(Node* root1,Node *root2){
        if(root1 == nullptr) return root2;
        if(root2 == nullptr) return root1;
        if(root1->val < root2->val) swap(root1,root2);
        root2->sibling = root1->child;
        root1->child = root2;
        root1->rang++;
        return root1;
    }

    Node* merge_heap(Node* root1){
        if(root1 == nullptr or root1->sibling == nullptr) return root1;
        queue<Node*> q;
        while(root1 != nullptr){
            Node* n1 = root1;
            Node* n2 = root1->sibling;
            root1 = n2->sibling;
            n1->sibling = nullptr;
            n2->sibling = nullptr;
            q.push(merge_(n1,n2));
        }
        while(q.size()>=2) {
            Node* n1 = q.front();
            q.pop();
            Node* n2 = q.front();
            q.pop();
            q.push(merge_(n1,n2));
        }
        return q.front();
    }

public:
    Rank_Pairing_Heap() : root(nullptr) {}

    Node* get_root(){
        return root;
    }

    bool empty() const {
        return root == nullptr;
    }

    int top() const {
        return root->val;
    }

    void push(int nr){
        Node* aux = new Node(nr);
        root = merge_(root, aux);
    }

    void pop(){
        Node* last_root = root;
        root = merge_heap(root->child);
        delete last_root;
    }

    void heap_union( Rank_Pairing_Heap &h2 ){
        root = merge_(root,h2.get_root());
    }

};

Rank_Pairing_Heap H[NMAX];

int main()
{
    int N,Q,operatie,x,y,m;
    fin >> N >> Q;
    for(int t=1;t<=Q;t++){
        fin >> operatie;
        if(operatie == 1){
            fin >> m >> x;
            H[m].push(x);
        }
        if(operatie == 2){
            fin >> m;
            fout << H[m].top() << '\n';
            H[m].pop();
        }
        if(operatie == 3){
            fin >> x >> y;
            H[x].heap_union(H[y]);
        }
    }
    return 0;
}