binary-heap

how to determine if the kth largest element of the heap is greater than x

守給你的承諾、 提交于 2019-11-27 04:03:59
问题 Consider a binary heap containing n numbers (the root stores the greatest number). You are given a positive integer k < n and a number x. You have to determine whether the kth largest element of the heap is greater than x or not. Your algorithm must take O(k) time. You may use O(k) extra storage 回答1: Simple dfs can do the job. We have a counter set to zero. Start from the root and in each iteration check the value of current node; if it is greater than x, then increase the counter and

How can std::make_heap be implemented while making at most 3N comparisons?

谁说胖子不能爱 提交于 2019-11-26 10:36:00
问题 I looked in to the C++0x standard and found the requirement that make_heap should do no more than 3*N comparisons. I.e. heapify an unordered collection can be done in O(N) /* @brief Construct a heap over a range using comparison functor. Why is this? The source gives me no clues (g++ 4.4.3) The while (true) + __parent == 0 are not clues but rather a guess for O(N) behaviour template<typename _RandomAccessIterator, typename _Compare> void make_heap(_RandomAccessIterator __first,