-
Notifications
You must be signed in to change notification settings - Fork 105
/
Merge_k_Sorted_Arrays.CPP
72 lines (58 loc) · 1.29 KB
/
Merge_k_Sorted_Arrays.CPP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
//Initial Template for C++
#include<bits/stdc++.h>
#define N 105
using namespace std;
void printArray(vector<int> arr, int size)
{
for (int i=0; i < size; i++)
cout << arr[i] << " ";
}
// } Driver Code Ends
//User function Template for C++
class Solution
{
public:
//Function to merge k sorted arrays.
vector<int> mergeKArrays(vector<vector<int>> arr, int K)
{
//code here
vector<int>count(K,0);
vector<int>v;
priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>>p;
for(int i=0;i<K;i++)
p.push({arr[i][0],i});
while(!p.empty())
{
v.push_back(p.top().first);
int x=p.top().second;
p.pop();
count[x]++;
if(count[x]<K)
p.push({arr[x][count[x]],x});
}
return v;
}
};
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--){
int k;
cin>>k;
vector<vector<int>> arr(N, vector<int> (N, 0));
for(int i=0; i<k; i++){
for(int j=0; j<k; j++)
{
cin>>arr[i][j];
}
}
Solution obj;
vector<int> output = obj.mergeKArrays(arr, k);
printArray(output, k*k);
cout<<endl;
}
return 0;
}
// } Driver Code Ends