Pagini recente » Cod sursa (job #104532) | Cod sursa (job #3129972) | Cod sursa (job #294679) | Cod sursa (job #3139904) | Cod sursa (job #3126359)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream f("mergeheap.in");
ofstream g("mergeheap.out");
class PairingHeap {
private:
struct Node {
int data;
Node* child;
Node* next;
Node* prev;
Node(const int& value) : data(value), child(nullptr), next(nullptr), prev(nullptr) {}
};
Node* root;
void clear(Node* node) {
if (node == nullptr) {
return;
}
if (node->child != nullptr) {
clear(node->child);
}
if (node->next != nullptr) {
clear(node->next);
}
delete node;
}
Node* mergePairs(Node* first) {
if (first == nullptr || first->next == nullptr) {
return first;
}
Node* second = first->next;
Node* rest = second->next;
first->next = nullptr;
second->next = nullptr;
Node* merged = merge(merge(first, second), mergePairs(rest));
return merged;
}
public:
PairingHeap() : root(nullptr) {}
~PairingHeap() {
clear(root);
}
void insert(const int& value) {
Node* node = new Node(value);
root = merge(root, node);
}
int findMax() const {
return root->data;
}
void deleteMax() {
Node* oldRoot = root;
root = mergePairs(root->child);
delete oldRoot;
}
bool isEmpty() const {
return root == nullptr;
}
void merge(PairingHeap& other) {
root = merge(root, other.root);
other.root = nullptr;
}
Node* merge(Node* first, Node* second) {
if (first == nullptr) {
return second;
}
if (second == nullptr) {
return first;
}
if (first->data > second->data) {
second->prev = first;
first->next = second->child;
if (second->child != nullptr) {
second->child->prev = first;
}
first->child = second;
return first;
} else {
first->prev = second;
second->next = first->child;
if (first->child != nullptr) {
first->child->prev = second;
}
second->child = first;
return second;
}
}
};
int main()
{
int N, Q;
f >> N >> Q;
PairingHeap heap[N];
for (int i = 0; i < Q; i++)
{
int op, m, x, y;
f >> op;
switch (op)
{
case 1:
f >> m >> x;
heap[m].insert(x);
break;
case 2:
f >> m;
g << heap[m].findMax()<< endl;
heap[m].deleteMax();
break;
case 3:
f >> x >> y;
heap[x].merge(heap[y]);
break;
}
}
return 0;
}