Cod sursa(job #3126445)

Utilizator PatrunjelxdVarona Antoniu Patrunjelxd Data 6 mai 2023 17:15:11
Problema Heapuri cu reuniune Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.19 kb
#include <iostream>
#include <fstream>

using namespace std;

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

class PairingHeap{
    class Node{
    public:
        int data;
        Node* child;
        Node* next;
        Node(int data){
            this->data = data;
            child = nullptr;
            next = nullptr;
        }
    };
    Node* root;
    public:
    PairingHeap(){
        root = nullptr;
    }
    void insert(int data){
        Node* node = new Node(data);
        if(root == nullptr){
            root = node;
        }else{
            root = merge(root, node);
        }
    }
    Node* merge(Node* node1, Node* node2){
        if(node1 == nullptr){
            return node2;
        }
        if(node2 == nullptr){
            return node1;
        }
        if(node1->data < node2->data){
            Node* temp = node1;
            node1 = node2;
            node2 = temp;
        }
        Node* child = node1->child;
        if (child == nullptr) {
            node1->child = node2;
        } else {
            while (child->next != nullptr) {
                child = child->next;
            }
            child->next = node2;
        }
        return node1;
    }
    int getMax(){
        return root->data;
    }
    void extractMax(){
        Node* current = root->child;
            root = nullptr;
            while(current!=nullptr)
            {
                Node* next = current->next;
                current->next = nullptr;
                root = merge(root,current);
                current = next;
            }
    }
    PairingHeap merge(PairingHeap heap1, PairingHeap heap2){
        PairingHeap heap;
        heap.root = merge(heap1.root, heap2.root);
        return heap;
    }
};

int main() {
    int n, q;
    fin>>n;
    PairingHeap heap[101];
    fin>>q;
    for(int i=0;i<q;i++){
        int a,b,c;
        fin>>a;
        if(a==1){
            fin>>b>>c;
            heap[b].insert(c);
        }
        else if(a==2){
            fin>>b;
            fout<<heap[b].getMax()<<endl;
            heap[b].extractMax();
        }
        else if(a==3){
            fin>>b>>c;
            heap[b]=heap[b].merge(heap[b],heap[c]);
        }
        }
    return 0;
    }