算法4 Java解答 2.4.18
2.4.18
问题:
2.4.18 In MaxPQ, suppose that a client calls insert() with an item that is larger than all items in the queue, and then immediately calls delMax(). Assume that there are no duplicate keys. Is the resulting heap identical to the heap as it was before these op- erations? Answer the same question for two insert() operations (the first with a key larger than all keys in the queue and the second for a key larger than that one) followed by two delMax() operations.
分析:
一、假设所有的Key都不相同 对于insert, delMax 元素的上升路径a1,a2,a3, … , ak. ak为待插入元素,a1为根节点。 insert后以上元素的顺序变为 ak, a1, a2, a3, … , ak-1 delMax,ak-1, a1, a2, …, ak-2 由于ak-2大于ak-1,所以ak-1原路返回。
对于insert,insert,delMax,delMax 同理。 堆不变。
二、假设假设上升路径上有的元素Key相同。 一个极端情况,假设堆在插入新元素之前所有的key都相同。 元素的上升路径a1,a2,a3, … , ak. ak为待插入元素,a1为根节点。 insert后以上元素的顺序变为 ak, a1, a2, a3, … , ak-1 delMax,ak-1, a1, a2, …, ak-2 ak-1 = a1, a2, … 所以ak-1的位置不会改变,那么结论是堆变了。