Created
June 10, 2014 23:14
-
-
Save zahlenteufel/3eaac2ce492ef19be149 to your computer and use it in GitHub Desktop.
K-Way Merge using C++11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T> | |
using minheap = priority_queue<T, vector<T>, greater>; | |
vector<int> kwaymerge(vector<vector<int>>& vs) { | |
int k = vs.size(); | |
vector<int> readcount(k, 0); | |
vector<int> res; | |
vector<pair<int, int>> vec; | |
for (int i = 0; i < k; i++) { | |
if (vs[i].size() > 0){ | |
vec.push_back(make_pair(vs[i].front(), i)); | |
readcount[i]++; | |
} | |
} | |
// this way it uses heapify | |
minheap q(vec.begin(), vec.end()); | |
while (!q.empty()) { | |
int v = q.top().first, i = q.top().second; q.pop(); | |
res.push_back(v); | |
if (readcount[i] < vs[i].size()) { | |
vec.push_back(make_pair(vs[i][readcount[i], i)); | |
readcount[i]++; | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment