problem: Design an algorithm to combine K ordered linked lists into an ordered list, known as the total number of K-linked list elements N.
The complexity required by the algorithm is O (NLOGK), can use the smallest heap to achieve K-way merge, the specific algorithm is as follows:
1. Remove the K-Link head node and adjust it to a minimum heap heap[k];
2. Remove the minimum value from the heap heap, then place the lowest value next node in the heap[0] position, and then adjust the heap to become the minimum heap again. Enter the minimum value the next node does not exist, delete heap[0], adjust the minimum heap heap, the number of elements minus one.
3. Repeat step 2 to know that the K list is empty.
The C + + code is as follows:
#include <iostream>
using namespace Std;
struct node{
int value;
Node*next;
};
Node *build_node (int m); Create a linked list with an element count of M
void Minheap_pihy (Node *a[], int n, int i);
void Buildminheap (Node *a[], int n); Build Minimum Heap
Node*push (node*a[], int n); Returns the top element of the heap and the number of heap elements minus one
Node*mergek (node*heap[], int k,int n); K-Road Merge
void Print_node (Node*head) {
Node*p = head;
while (p) {
cout << p->value << "";
p=p->next;
}
cout << Endl;
}
int main () {
int m1,m2,m3;
Node*heap[3]{null};
CIN >> M1;
Heap[0] = Build_node (M1);
cin >> m2;
HEAP[1] = Build_node (m2);
Cin >> M3;
HEAP[2] =build_node (m3);
Node*head = Mergek (heap, 3,m1+m2+m3);
Print_node (head);
return 0;
}
Node *build_node (int m) {
Node*head = new Node;
NODE*P1 = head, *p2 = head;
CIN >> head->value;
for (int i = 1; i < m; i++) {
P1 = new Node;
CIN >> p1->value;
P2->next = p1;
P2 = p2->next;
}
P2->next = NULL;
return head;
}
void Minheap_pihy (node*a[], int n, int i) {//In a, adjust the first element down filter
int left,child;
for (left = i * 2 + 1, left <n; left = i * 2 + 1) {
Child = i;
if (A[left]->value<a[child]->value)
Child = left;
if (left + 1 <n&&a[left + 1]->value<a[child]->value)
Child = left + 1;
if (i = = child)
Break
Swap (A[child], a[i]);
i = child;
}
}
void Buildminheap (node* a[], int n) {
for (int i = N/2-1; I >= 0; i--)
Minheap_pihy (A, n, i);
}
Node*push (node*a[], int n) {
Node*p = a[0];
A[0] = a[n-1];
Minheap_pihy (A, n-1, 0);
return p;
}
Node*mergek (node*heap[], int k,int n) {
Node*head = new Node; Set a short node
NODE*P1 = head, *p2 = head;
Buildminheap (heap, k);
for (int i = 0; i < n; i++) {
if (heap[0]->next== NULL) {//heap top element next node is empty
P1 = Push (heap, k);
k--;
}
else{
P1 = heap[0];
Heap[0] = p1->next;
Minheap_pihy (heap, K, 0);
}
p2->next=p1;
P2 = p2->next;
}
P2->next = NULL;
P1 = head;
Head = head->next;
Delete P1; Delete a short node.
return head;
}
Multi-Path Merge