#include <vector> #include <iostream> #include <queue>using namespace std;/* Write a program that takes a n input a set of sorted sequences and compute the union of these sequences as a sorted sequence. For example: [3, 5, 7], [0, 6, 8], [0, 6, +], then the output was [0, 0, 3, 5, 6, 6, 7, 28]*//* this problem can further be divided into. 1:there is only sorted sets. 2:the number of input sets is more than two.*///time Complexity:o (n), Space O (n) vector<int> mergetwosets (vector& lt;int>& set_1, vector<int>& set_2) {int m = set_1.size (); if (M = = 0) return set_2; int n = set_2.size (); if (n = = 0) return set_1; vector<int> Res; int i = 0, j = 0; while (I < m && J < N) {if (Set_1[i] <= set_2[j]) {res.push_back (set_1[i++]); } else {res.push_back (set_2[j++]); }} while (I < m) {Res.push_back (set_1[i++]); } while (J < n) {Res.push_back (set_2[j++]); } return res; void PRintvector (vector<int>& Res) { for (int i = 0; i < res.size (); ++i) { cout << re S[i] << endl; }}//identical with merging multiple sorted lists. Time Complexity:nlgk (K is the number of input size). Space lgkvector<int> mergemultisets (const vector< vector<int> >& sets) { struct Iteratorstartandend { BOOL Operator < (const iteratorstartandend& that) const { & nbsp; return *start > *that.start; } vector<int>::const_ Iterator start; vector<int>::const_iterator end; }; priority_queue< Iteratorstartandend, vector<iteratorstartandend> > minheap; for (const vector<int>& SORTED_ Array:sets) { if (!sorted_array.empty ()) Minheap.push (iteratorstartandend{ Sorted_array.cbegin (), Sorted_array.cend ()}); } VECTOR<INT> res; while (!minheap.empty ()) { Auto Smallest_array = minheap.top (); Minheap.pop (); if (smallest_array.start ! = smallest_array.end) { Res.push_back (*smallest_array.start); Minheap.push (IteratorStartAndEnd{next (Smallest_array.start), smallest_array.end}); } } return res;} int main (void) { vector<int> set_1{0, 15}; vector<int> set_2{2, 3, ten, 12}; VECTOR<INT&G T Set_3{2, 3, 9, 14};// vector<int> res = mergetwosets (set_1, set_2); //printvector (res); vector& Lt vector<int> > multisets; multisets.push_back (set_1); multisets.push_back (set_2); Multisets.push_back (set_3); vector<int> res_1 = mergemultisets (multisets); printVector (res_1);}
EPI (HEAP) Merge multiple sorted arrays.