Advertisement
kartikkukreja

Multiway Merge with STL heaps

Jun 25th, 2013
120
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. #include <cstdio>
  2. #include <vector>
  3. #include <algorithm>
  4. #include <cstring>
  5.  
  6. using namespace std;
  7.  
  8. typedef pair <int, int> ii;
  9. typedef vector <int> vi;
  10. typedef vector <ii> vii;
  11.  
  12. // comparator for min-heap
  13. // By default, heap functions create a max-heap
  14. bool comp(ii x, ii y)   {
  15.     return x > y;
  16. }
  17.  
  18. int main()  {
  19.     int N = 3;  // number of sorted vectors
  20.     vi* A = new vi[N];  // array of sorted vectors
  21.     int *indices = new int[N]; // stores the index of the next element to be added to the heap in each array
  22.  
  23.     A[0].push_back(3); A[0].push_back(5); A[0].push_back(6); A[0].push_back(10);
  24.     A[1].push_back(1); A[1].push_back(2); A[1].push_back(7);
  25.     A[2].push_back(2); A[2].push_back(4); A[2].push_back(6); A[2].push_back(8);
  26.  
  27.     // initially, first elements of each vector are added to the heap so the index
  28.     // of next element to be added to the heap for each vector is 1.
  29.     for (int i = 0; i < N; i++)
  30.         indices[i] = 1;
  31.  
  32.     // vector that forms the heap. pairs of elements and vector number form the elements of the heap
  33.     // vector number is used to identify the vector this element was added from so that the next element
  34.     // can be added from the same vector
  35.     vii heap;
  36.  
  37.     // first element of each vector is added to the heap
  38.     for (int i = 0; i < N; i++)
  39.         heap.push_back(make_pair(A[i][0], i));
  40.  
  41.     make_heap(heap.begin(), heap.end(), comp);
  42.  
  43.     // while the heap is not empty, remove the minimum element from the heap, print it
  44.     // and add the next element from the vector this element was added to the heap
  45.     while(!heap.empty())    {
  46.         pair <int, int> mn = heap.front();
  47.         printf("%d ", mn.first);
  48.  
  49.         pop_heap(heap.begin(), heap.end(), comp);
  50.         heap.pop_back();
  51.  
  52.         int pos = mn.second;
  53.  
  54.         if (indices[pos] < A[pos].size())   {
  55.             heap.push_back(make_pair(A[pos][indices[pos]++], pos));
  56.             push_heap(heap.begin(), heap.end(), comp);
  57.         }
  58.     }
  59.  
  60.     return 0;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement