Блог пользователя xuanquang1999

Автор xuanquang1999, история, 9 лет назад, По-английски

I'm trying to solve 103 — Stacking Boxes on UVa online judge. My idea is first, sort all the box that no box can be nested in the previous box, then run O(n^2) LIS DP on it.

However, when I print the order and the sizes of all boxes, I found something weird:

The Bubble sort algorithm gave correct sorting order:

Code used Bubble sort

But std::sort gave wrong sorting order (more specific, box 5 should stay before box 1):

Code used std::sort

std::stable_sort also gave wrong sorting order:

Code used std::stable_sort

Did something go wrong with my implementation? Or something went wrong with std::sort and std::stable_sort?

  • Проголосовать: нравится
  • +1
  • Проголосовать: не нравится

»
9 лет назад, # |
  Проголосовать: нравится +6 Проголосовать: не нравится

There are two requirements for comparator if you want general sorting algorithms to work:

1) comparator should be transitive.

2) Let's call elements a and b uncomparable if both a < b and b < a are false. Then uncomparability should be equivalence relation (transitive, reflexive and symmetric).

Clearly, your comparator does not satisfy second quality (uncomparability is not transitive). Bubble sort uses only local comparisons, so it may work in this case (because there exist permutation that "is sorted" according to this comparator), but faster algorithms that use bigger knowledge about comparator to fasten up (if comparator only satisfies quality 1, then only topological sorting is guaranteed to work for any comparator satisfying this quality, which is too slow) may produce incorrect result.