forked from akibzaman/Beginners-Data-Structure
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmergeKSorted.cpp
70 lines (54 loc) · 1.24 KB
/
mergeKSorted.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
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> PAIR;
int main()
{
int k;
cin >> k;
vector<vector<int>> allValues(k);
//Input
for (int i = 0; i < k; i++)
{
int size;
cin >> size;
allValues[i] = vector<int>(size);
for (int k = 0; k < size; k++)
{
cin >> allValues[i][k];
}
}
vector<int>indexTracker(k,0);
priority_queue<PAIR, vector<PAIR>, greater<PAIR>> PQ;
//Initialisation of PQ
for(int i=0; i<k;i++){
PQ.push(make_pair(allValues[i][0],i));
}
vector<int>ans;
// Main Logic of Heap
while(!PQ.empty()){
PAIR x = PQ.top();
PQ.pop();
ans.push_back(x.first);
if(indexTracker[x.second]+1 < allValues[x.second].size()){ //increment position Validity Check
PQ.push(make_pair(allValues[x.second][indexTracker[x.second]+1], x.second));
//We are Creating a pair: (increment position value, increment position array identity )
//Then Push in PQ
}
indexTracker[x.second]+=1;
}
//Print Ans
for(auto element:ans){
cout<< element << " ";
}
cout<< endl <<endl;
return 0;
}
/*
3
3
1 4 7
2
3 5
3
2 6 7
*/