Cod sursa(job #3227847)

Utilizator alexnohai04Nohai Alexandru alexnohai04 Data 3 mai 2024 00:28:57
Problema Heapuri cu reuniune Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.5 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

ifstream f("mergeheap.in");
ofstream g("mergeheap.out");

class Node {
public:
    int val;
    int rank;
    Node* child;
    Node* sibling;
    Node(int _val = 0) : val(_val), rank(0), child(nullptr), sibling(nullptr) {}
};

class RankPairingHeap {
public:
    Node* root;

    
    RankPairingHeap() : root(nullptr) {}
    ~RankPairingHeap() {
        clear(root);
    }

    // Utility function to clear the heap recursively
    void clear(Node* n) {
        if (!n) return;
        clear(n->child);
        clear(n->sibling);
        delete n;
    }

    // Merge two heaps
    Node* merge(Node* root1, Node* root2) {
        if (!root1) return root2;
        if (!root2) return root1;
        if (root2->val < root1->val) swap(root1, root2);

        root2->sibling = root1->child;
        root1->child = root2;
        if (root1->rank == root2->rank) root1->rank++;
        return root1;
    }

    // Merge pairs of trees in the root list
    Node* mergePairs(Node* start) {
        if (!start || !start->sibling) return start;
        Node* n1 = start;
        Node* n2 = start->sibling;
        Node* remaining = n2->sibling;
        n1->sibling = nullptr;
        n2->sibling = nullptr;
        return merge(merge(n1, n2), mergePairs(remaining));
    }

    // Public interface to merge with another heap
    void mergeWith(RankPairingHeap& other) {
        root = merge(root, other.root);
        other.root = nullptr;
    }

    // Find the minimum value in the heap
    int findMin() {
        return root ? root->val : -1;
    }

    // Insert a new value into the heap
    void insert(int value) {
        Node* newNode = new Node(value);
        root = merge(root, newNode);
    }

    // Delete the minimum value in the heap
    void deleteMin() {
        if (!root) return;
        Node* oldRoot = root;
        root = mergePairs(root->child);
        delete oldRoot;
    }
};

RankPairingHeap R[102];

int main() {
    int N, Q, x, y, m, opt;
    f >> N >> Q;
    for (int t = 1; t <= Q; t++) {
        f >> opt;
        if (opt == 1) {
            f >> m >> x;
            R[m].insert(x);
        }
        else if (opt == 2) {
            f >> m;
            g << R[m].findMin() << '\n';
            R[m].deleteMin();
        }
        else if (opt == 3) {
            f >> x >> y;
            R[x].mergeWith(R[y]);
        }
    }
    return 0;
}