Advertisement
satishfrontenddev5

Untitled

Jan 6th, 2024
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. /*
  2. Given K sorted arrays, possibly of different sizes, merge them and print the sorted output.
  3.  
  4. Input format
  5. First line contains an integer K - Number of arrays.
  6.  
  7. For each array there is two lines of input:
  8.  
  9. First line contains an integer n - Size of array.
  10.  
  11. Second line contains n integers - The array.
  12.  
  13. Output format
  14. Print in single line, the elements in sorted order.
  15.  
  16. Sample Input 1
  17. 3
  18.  
  19. 3
  20.  
  21. 2 4 7
  22.  
  23. 1
  24.  
  25. 8
  26.  
  27. 4
  28.  
  29. 2 5 5 9
  30.  
  31. Sample Output 1
  32. 2 2 4 5 5 7 8 9
  33.  
  34. Explanation
  35. Elements of 1st array - 2, 4, 7.
  36.  
  37. Elements of 2nd array - 8.
  38.  
  39. Elements of 3rd array - 2, 5, 5, 9.
  40.  
  41. Merging the elements and printing them in sorted order will give - 2, 2, 4, 5, 5, 7, 8, 9.
  42.  
  43. Constraints
  44. 1 <= K <= 10^5
  45.  
  46. 1 <= n <= 10^5
  47.  
  48. -10^6<= Array elements <= 10^6
  49.  
  50. Note: Total number of elements will be less than 10^6.
  51. */
  52.  
  53. struct comparator{
  54.     bool operator()(pair<int, pair<int,int>>&p1,pair<int, pair<int,int>>&p2){
  55.         return p1.first>p2.first;
  56.     }
  57. };
  58.  
  59. vector<int> mergeKSortedArrays(vector<vector<int>> arrays){
  60.     vector<int>ans;
  61.     int k=arrays.size();
  62.     int i,j;
  63.     priority_queue< pair<int, pair<int,int>>,
  64.     vector< pair<int, pair<int,int>> >,
  65.     comparator
  66.     > pq;
  67.     // pair< arr[i][j],pair<i,j>>
  68.     // arr[i][j] : jth value in i-th array
  69.     // i: i-th array (arrayIndex)
  70.     // j: IndexInArray  
  71.     for(i=0;i<k;i++){
  72.         // if(arrays[i].size()>0)
  73.          pq.push({arrays[i][0],{i,0}});
  74.     }
  75.  
  76.     while(!pq.empty()){
  77.         auto top=pq.top();
  78.         pq.pop();
  79.         int value=top.first;
  80.         int arrayIndex=top.second.first;
  81.         int IndexInArray=top.second.second;
  82.         int currentArraySize=arrays[arrayIndex].size();
  83.  
  84.  
  85.         ans.push_back(value);
  86.  
  87.         if(IndexInArray+1<currentArraySize){
  88.             int newValue=arrays[arrayIndex][IndexInArray+1];
  89.             pq.push({newValue,{arrayIndex,IndexInArray+1}});
  90.         }
  91.     }
  92.  
  93.         return ans;
  94.  
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement