Is partial-order, in contrast to total-order, enough to build a heap?

自闭症网瘾萝莉.ら 提交于 2019-12-02 09:43:56

问题


C++ std::priority_queue just need a partial order. But if its implementation is a binary heap, how does it works? For example: assume we have a partially ordered set ( {a, b, c, x}, {c < b, b < a, c < a} ), x has nothing to do with a, b, c. Then a max-heap is:

layer 1:    x
layer 2:  b   x
layer 3: x x a c

After a pop operation, in a way commonly seen in text books, i.e. replace the root with c and decrease the size by 1. Then we need to heapify the tree below, at the root:

layer 1:    c
layer 2:  b   x
layer 3: x x a

We will swap c and b as c < b, won't we? And what? We still don't have a valid heap since b < a. But b cannot "see" a.


回答1:


The requirement for priority_queue is (§23.6.4 of the C++ Standard) that the comparator defines a strict, weak ordering. The latter is defined in §25.4/4 as follows:

The term strict refers to the requirement of an irreflexive relation (!comp(x, x) for all x), and the term weak to requirements that are not as strong as those for a total ordering, but stronger than those for a partial ordering. If we define equiv(a, b) as !comp(a, b) && !comp(b, a), then the requirements are that comp and equiv both be transitive relations:

— comp(a, b) && comp(b, c) implies comp(a, c)

— equiv(a, b) && equiv(b, c) implies equiv(a, c) [ Note: Under these conditions, it can be shown that

i) equiv is an equivalence relation

ii) comp induces a well-defined relation on the equivalence classes determined by equiv

iii) The induced relation is a strict total ordering. — end note ]

In other words, the comparator-defined relation does not have to be total, but it must be total with respect to the equivalence classes defined by a hypothetical relation equiv, which defines all elements as equal that are not less-than or greater-than each other.

To put it in even simpler terms, any elements not covered by the comparator relation will be treated as equal.



来源:https://stackoverflow.com/questions/12419603/is-partial-order-in-contrast-to-total-order-enough-to-build-a-heap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!