Guest User

Untitled

a guest
Oct 18th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <vector>
  5. #include <iterator>
  6.  
  7. using namespace std;
  8.  
  9. bool compare(int a, int b)
  10. {
  11. // child > parent
  12. return a > b;
  13. }
  14.  
  15. // Time complexity: O(n*lgk)
  16. vector<int> getLargestK(const vector<int>& input, size_t k)
  17. {
  18. vector<int>::const_iterator itLeft = input.begin() + k;
  19. vector<int> heap(input.begin(), itLeft);
  20. make_heap(heap.begin(), heap.end(), &compare);
  21. //copy(heap.begin(), heap.end(), ostream_iterator<int>(cout, " "));
  22. //cout << endl;
  23.  
  24. for(vector<int>::const_iterator it = itLeft; it != input.end(); ++it)
  25. {
  26. if(compare(*it, heap[0]))
  27. {
  28. pop_heap(heap.begin(), heap.end(), &compare);
  29. heap[k-1] = *it;
  30. push_heap(heap.begin(), heap.end(), &compare);
  31. //copy(heap.begin(), heap.end(), ostream_iterator<int>(cout, " "));
  32. //cout << endl;
  33. }
  34. }
  35.  
  36. copy(heap.begin(), heap.end(), ostream_iterator<int>(cout, " "));
  37. cout << endl;
  38.  
  39. return heap;
  40. }
  41.  
  42. int main()
  43. {
  44. int array[] = {1, 2, 3, 4, 5, 8, -1, 3, 6};
  45. vector<int> input(array, array+sizeof(array)/sizeof(array[0]));
  46.  
  47. getLargestK(input, 1);
  48.  
  49. getLargestK(input, 2);
  50.  
  51. getLargestK(input, 3);
  52.  
  53. getLargestK(input, 4);
  54.  
  55. getLargestK(input, 5);
  56.  
  57. getLargestK(input, 6);
  58.  
  59. getLargestK(input, 7);
  60.  
  61. }
Add Comment
Please, Sign In to add comment