fork download
  1. #include<iostream>
  2. #include<queue>
  3. #include<vector>
  4. using namespace std;
  5.  
  6. typedef pair<int, pair<int,int> > node;
  7. vector<int> mergeKSortedArray(vector<vector<int> > arr){
  8. vector<int>result;
  9. priority_queue<node, vector<node>, greater<node> > pq;//min priority queue
  10. //insert 0th element of each arr to pq
  11. for(int i=0;i<arr.size();i++){
  12. pq.push({arr[i][0],{i,0}});//we need to store 3 things - val of ele, index of arr, index of ele
  13. }
  14. //remove the ele one by one from min heap and add it to the result vector
  15. while(!pq.empty()){
  16. node current = pq.top();
  17. pq.pop();
  18. int element = current.first;
  19. int x = current.second.first;//row in which element is present
  20. int y = current.second.second;//col in which element is present
  21.  
  22. result.push_back(element);
  23. //you need to push in pq the next element of current x,y+1
  24. if(y+1<arr.size()){
  25. pq.push({arr[x][y+1],{x,y+1}});
  26. }
  27. }
  28. return result;
  29. }
  30. int main(){
  31. int n,k,ele;
  32. cin>>n>>k;
  33. /*vector<vector<int> >arr{{2,6,12,15},
  34.   {1,3,14,20},
  35.   {3,5,8,10}};*/
  36. vector<vector<int> > arr;
  37.  
  38. for (int i = 0; i < n; i++) {
  39.  
  40. vector<int> v1;
  41.  
  42. for (int j = 0; j < k; j++) {
  43. cin>>ele;
  44. v1.push_back(ele);
  45. }
  46. arr.push_back(v1);
  47. }
  48. vector<int>output = mergeKSortedArray(arr);
  49. for(int i=0;i<output.size(); i++){
  50. cout<<output[i]<<" ";
  51. }
  52.  
  53.  
  54.  
  55. return 0;}
  56.  
Time limit exceeded #stdin #stdout 5s 2100372KB
stdin
Standard input is empty
stdout
Standard output is empty