Pagini recente » Cod sursa (job #2032496) | Cod sursa (job #1052700) | Cod sursa (job #1984834) | Cod sursa (job #2857603) | Cod sursa (job #3126707)
#include <bits/stdc++.h>
using namespace std;
struct HeapNode {
int val;
HeapNode *left, *mid, *right;
HeapNode(int v) : val(v), left(NULL), mid(NULL), right(NULL) {}
};
HeapNode *merge(HeapNode *a, HeapNode *b) {
if (!a) return b;
if (!b) return a;
if (a->val < b->val) swap(a, b);
if (!a->mid) {
a->mid = b;
}
else {
a->right = merge(a->right, b);
if (a->right && a->right->val > a->mid->val) {
swap(a->mid, a->right);
swap(a->left, a->mid);
}
if (a->right && a->right->val > a->val) {
swap(a->val, a->right->val);
if (a->right->val > a->mid->val) {
swap(a->mid, a->right);
swap(a->left, a->mid);
}
}
}
return a;
}
int find_max(HeapNode *root) {
if (!root) return 0;
if (!root->mid) return root->val;
if (!root->right) return max(root->val, find_max(root->mid));
return max(root->val, max(find_max(root->mid), find_max(root->right)));
}
HeapNode *delete_max(HeapNode *root) {
if (!root->mid) {
HeapNode *temp = root;
root = root->left;
delete temp;
}
else if (!root->right) {
swap(root->val, root->mid->val);
HeapNode *temp = root->mid;
root->mid = NULL;
delete temp;
}
else {
if (root->right->val > root->mid->val) {
swap(root->val, root->right->val);
swap(root->right, root->mid);
root->mid = delete_max(root->mid);
}
else {
swap(root->val, root->mid->val);
root->mid = delete_max(root->mid);
}
}
return root;
}
int main() {
int n, q;
ifstream cin("mergeheap.in");
ofstream cout("mergeheap.out");
cin >> n >> q;
vector<HeapNode *> heaps(n, NULL);
while (q--) {
int op, x, y;
cin >> op;
if (op == 1) {
cin >> x >> y;
heaps[x-1] = merge(heaps[x-1], new HeapNode(y));
}
else if (op == 2) {
cin >> x;
cout << find_max(heaps[x-1]) << "\n";
heaps[x-1] = delete_max(heaps[x-1]);
}
else {
cin >> x >> y;
heaps[x-1] = merge(heaps[x-1], heaps[y-1]);
heaps[y-1] = NULL;
}
}
return 0;
}