Cod sursa(job #2824574)

Utilizator UnknownPercentageBuca Mihnea-Vicentiu UnknownPercentage Data 2 ianuarie 2022 18:03:58
Problema Heapuri cu reuniune Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.62 kb
#include <bits/stdc++.h>

using namespace std;

inline void Open(const string Name) {
    #ifndef ONLINE_JUDGE
        (void)!freopen((Name + ".in").c_str(), "r", stdin);
        (void)!freopen((Name + ".out").c_str(), "w", stdout);
    #endif
}

struct HeapNode {
    int key;
    HeapNode *lc;
    HeapNode *nxts;

    HeapNode() : lc(nullptr), nxts(nullptr) {}
    HeapNode(int key_, HeapNode *lc_, HeapNode *nxts_) : key(key_), lc(lc_), nxts(nxts_) {}

    void addChild(HeapNode *node) {
        if(lc == nullptr) {
            lc = node;
            return;
        }

        node -> nxts = lc;
        lc = node;
    }
};

bool Empty(HeapNode *node) {
    return (node == nullptr);
}

HeapNode *merge(HeapNode *a, HeapNode *b) {
    if(a == nullptr)
        return b;
    if(b == nullptr)
        return a;

    if(a -> key < b -> key) {
        a -> addChild(b);
        return a;
    } else {
        b -> addChild(a);
        return b;
    }

    return nullptr;
}

int Top(HeapNode *node) {
    return node -> key;
}

HeapNode *Insert(HeapNode *node, int key) {
    return merge(node, new HeapNode(key, nullptr, nullptr));
}

HeapNode *TwoPassMerge(HeapNode *node) {
    if(node == nullptr || node -> nxts == nullptr)
        return node;

    HeapNode *a, *b, *newnode;
    a = node;
    b = node -> nxts;

    newnode = node -> nxts -> nxts;
    a -> nxts = nullptr;
    b -> nxts = nullptr;

    return merge(merge(a, b), TwoPassMerge(newnode));
}

HeapNode *Delete(HeapNode *node) {
    return TwoPassMerge(node -> lc);
}

struct pairingHeap {
    HeapNode *root;

    pairingHeap() : root(nullptr) {}

    bool Empty(void) {
        return ::Empty(root);
    }

    int Top(void) {
        return ::Top(root);
    }

    void Insert(int key) {
        root = ::Insert(root, key);
    }

    void Delete(void) {
        root = ::Delete(root);
    }

    void Join(pairingHeap other) {
        root = ::merge(root, other.root);
    }
};

pairingHeap v[101];

int N, Q, op, x, y;

void solve() {
    cin >> N >> Q;
    while(Q--) {
        cin >> op;
        if(op == 1) {
            cin >> x >> y;
            v[x].Insert(-y);
        }

        if(op == 2) {
            cin >> x;
            cout << -v[x].Top() << "\n";
            v[x].Delete();
        }

        if(op == 3) {
            cin >> x >> y;
            v[x].Join(v[y]);
        }
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    Open("mergeheap");

    int T = 1;
    for(;T;T--) {
        solve();
    }

    return 0;
}