Алгоритм для слияния двух макс. "кучи"?

Ваш браузер отправляет HTTP-запрос GET: Удостоверьтесь, что Вы сделали, чтобы WebGet приписал на операции в контракте:

[ServiceContract]
public interface IUploadService
{
    [WebGet()]
    [OperationContract]
    string TestGetMethod(); // This method takes no arguments, returns a string. Perfect for testing quickly with a browser.

    [OperationContract]
    void UploadFile(UploadedFile file); // This probably involves an HTTP POST request. Not so easy for a quick browser test.
 }
24
задан templatetypedef 17 April 2013 в 19:10
поделиться

2 ответа

It depends on what the type of the heap is.

If it's a standard heap where every node has up to two children and which gets filled up that the leaves are on a maximum of two different rows, you cannot get better than O(n) for merge.

Just put the two arrays together and create a new heap out of them which takes O(n).

For better merging performance, you could use another heap variant like a Fibonacci-Heap which can merge in O(1) amortized.

Update: Note that it is worse to insert all elements of the first heap one by one to the second heap or vice versa since an insertion takes O(log(n)). As your comment states, you don't seem to know how the heap is optimally built in the beginning (again for a standard binary heap)

  1. Create an array and put in the elements of both heaps in some arbitrary order
  2. now start at the lowest level. The lowest level contains trivial max-heaps of size 1 so this level is done
  3. move a level up. When the heap condition of one of the "sub-heap"s gets violated, swap the root of the "sub-heap" with it's bigger child. Afterwards, level 2 is done
  4. move to level 3. When the heap condition gets violated, process as before. Swap it down with it's bigger child and process recursively until everything matches up to level 3
  5. ...
  6. when you reach the top, you created a new heap in O(n).

I omit a proof here but you can explain this since you have done most of the heap on the bottom levels where you didn't have to swap much content to re-establish the heap condition. You have operated on much smaller "sub heaps" which is much better than what you would do if you would insert every element into one of the heaps => then, you willoperate every time on the whole heap which takes O(n) every time.

Update 2: A binomial heap allows merging in O(log(n)) and would conform to your O(log(n)^2) requirement.

16
ответ дан 29 November 2019 в 00:13
поделиться

Две двоичные кучи размеров n и k могут быть объединены за O (log n * log k) сравнений. См.

Jörg-R. Сак и Томас Стрототт, Алгоритм объединения куч, Acta Informatica 22 (1985), 172-186.

8
ответ дан 29 November 2019 в 00:13
поделиться
Другие вопросы по тегам:

Похожие вопросы: