Pagini recente » Cod sursa (job #1364092) | Cod sursa (job #649470) | Cod sursa (job #1039619) | Cod sursa (job #860268) | Cod sursa (job #3127927)
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("mergeheap.in");
ofstream g("mergeheap.out");
// Heap structure
struct HeapNode {
int key;
HeapNode* leftChild;
HeapNode* nextSibling;
HeapNode() :
leftChild(NULL), nextSibling(NULL) {}
// creates a new node
HeapNode(int key_, HeapNode* leftChild_, HeapNode* nextSibling_) :
key(key_), leftChild(leftChild_), nextSibling(nextSibling_) {}
// Adds a child and sibling to the node
void addChild(HeapNode* node) {
if (leftChild == NULL)
leftChild = node;
else {
node->nextSibling = leftChild;
leftChild = node;
}
}
};
// Returns true if root of the tree
// is null otherwise returns false
bool Empty(HeapNode* node) {
return (node == NULL);
}
// Function to merge two heaps
HeapNode* Merge(HeapNode* A, HeapNode* B)
{
// If any of the two-nodes is null
// the return the not null node
if (A == NULL) return B;
if (B == NULL) return A;
// To maintain the min heap condition compare
// the nodes and node with minimum value become
// parent of the other node
if (A->key > B->key) {
A->addChild(B);
return A;
}
else {
B->addChild(A);
return B;
}
return NULL; // Unreachable
}
// Returns the root value of the heap
int Top(HeapNode* node) {
return node->key;
}
// Function to insert the new node in the heap
HeapNode* Insert(HeapNode* node, int key) {
return Merge(node, new HeapNode(key, NULL, NULL));
}
// This method is used when we want to delete root node
HeapNode* TwoPassMerge(HeapNode* node) {
if (node == NULL || node->nextSibling == NULL)
return node;
else {
HeapNode* A, * B, * newNode;
A = node;
B = node->nextSibling;
newNode = node->nextSibling->nextSibling;
A->nextSibling = NULL;
B->nextSibling = NULL;
return Merge(Merge(A, B), TwoPassMerge(newNode));
}
return NULL; // Unreachable
}
// Function to delete the root node in heap
HeapNode* Delete(HeapNode* node) {
return TwoPassMerge(node->leftChild);
}
struct PairingHeap {
HeapNode* root;
PairingHeap() :
root(NULL) {}
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);
}
};
// Driver Code
int main()
{
int n, q;
PairingHeap h[101];
f >> n >> q;
int operatie, m, x, y;
for (int i = 1;i <= q;i++)
{
f >> operatie;
if (operatie == 1)
{
f >> m >> x;
h[m].Insert(x);
}
if (operatie == 2)
{
f >> m;
cout << h[m].Top() << endl;
g << h[m].Top() << endl;
h[m].Delete();
}
if (operatie == 3)
{
f >> x >> y;
h[x].Join(h[y]);
}
}
return 0;
}