Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- struct HeapNode {
- int value;
- int index;
- int next_index;
- };
- struct Array {
- int amount;
- int index;
- int* arr;
- };
- struct Heap {
- HeapNode* head;
- int hp_size;
- };
- void MinHeapify(Heap* heap, int index);
- void Swap(Heap* heap, int index, int minimum) {
- HeapNode temp = heap->head[index];
- heap->head[index] = heap->head[minimum];
- heap->head[minimum] = temp;
- }
- int LeftChild(int index) { return 2 * index + 1; }
- int RightChild(int index) { return 2 * index + 2; }
- void ReplaceMin(Heap* heap, HeapNode small) {
- heap->head[0] = small;
- MinHeapify(heap, 0);
- }
- HeapNode ExtractMin(Heap* heap) { return heap->head[0]; }
- void MinHeapify(Heap* heap, int index) {
- int left_index = 2 * index + 1;
- int right_index = 2 * index + 2;
- int minimum = index;
- if (left_index < heap->hp_size &&
- heap->head[left_index].value < heap->head[minimum].value) {
- minimum = left_index;
- }
- if (right_index < heap->hp_size &&
- heap->head[right_index].value < heap->head[minimum].value) {
- minimum = right_index;
- }
- if (minimum != index) {
- Swap(heap, index, minimum);
- MinHeapify(heap, minimum);
- }
- }
- Heap* HeapCreate(HeapNode* arr, int size) {
- Heap* heap = new Heap();
- heap->head = arr;
- heap->hp_size = size;
- int mid_index = (heap->hp_size - 1) / 2;
- while (mid_index >= 0) {
- MinHeapify(heap, mid_index);
- --mid_index;
- }
- return heap;
- }
- int* Merge(Array* arrays, int array_num, int size) {
- int* res = new int[size * 2];
- HeapNode* head = new HeapNode[array_num];
- for (int i = 0; i < array_num; ++i) {
- head[i].value = arrays[i].arr[0];
- head[i].index = i;
- head[i].next_index = 1;
- }
- Heap* heap = HeapCreate(head, array_num);
- for (int count = 0; count < size; count++) {
- HeapNode root = ExtractMin(heap);
- res[count] = root.value;
- if (root.next_index < arrays[root.index].amount) {
- root.value = arrays[root.index].arr[root.next_index];
- root.next_index++;
- } else {
- root.value = __INT_MAX__;
- }
- ReplaceMin(heap, root);
- }
- delete heap;
- return res;
- }
- int main() {
- int array_num, size = 0;
- std::cin >> array_num;
- Array* arrays = new Array[array_num];
- for (int i = 0; i < array_num; i++) {
- std::cin >> arrays[i].amount;
- arrays[i].arr = new int[arrays[i].amount];
- for (int k = 0; k < arrays[i].amount; k++) {
- std::cin >> arrays[i].arr[k];
- size++;
- // std::cout << arrays[i].arr[k] << " ";
- }
- }
- int* res = Merge(arrays, array_num, size);
- for (int i = 0; i < size; i++) {
- std::cout << res[i] << " ";
- }
- std::cout << "\n";
- delete[] res;
- delete[] arrays;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement