Merging two partial (jointly overdetermined) sets of ordering information

前端 未结 3 695
南旧
南旧 2021-01-06 04:34

I have a web app with data in a grid. The user can reorder the columns, and the server can change which columns exist. I would like to save the user\'s column order in a coo

3条回答
  •  醉梦人生
    2021-01-06 05:39

    This relates to Niklas B's answer:

    Theorem: Consider a sequence S = s₁, …, sₙ of some orderet set (e.g. integers). If i < j and sᵢ > sⱼ, then swapping sᵢ and sⱼ decreases the number of inversions—that is, let S' = s₁, …, sᵢ₋₁, sⱼ, sᵢ₊₁, …, sⱼ₋₁, sᵢ, sⱼ₊₁, …, sₙ; then S' has fewer inversions than S.

    Intuitively stated: if two elements are out of order and you swap them, you're closer to having a sorted list.

    Proof: Observe that the only elements that have a different relative order in S and S' are (sᵢ, sⱼ), (sᵢ, sₖ) and (sⱼ, sₖ) for each k where i < k < j. We know that (sᵢ, sⱼ) is an inversion in S but not S', so consider sₖ for some such k.

    Either sₖ < sⱼ < sᵢ or sⱼ < sₖ < sᵢ or sⱼ < sᵢ < sₖ (we assume the elements of S to be unique).

    In the first case, (sᵢ, sₖ) is an inversion in S and (sⱼ, sₖ) is an inversion in S'. In the second case, (sᵢ, sₖ) and (sⱼ, sₖ) are inversions in S but not in S'. In the third case, (sⱼ, sₖ) is an inversion in S and (sᵢ, sₖ). These are all the changes in inversions.

    In each case, the number of inversions in S' is either the same as that in S or it is smaller. Recall that (sᵢ, sⱼ) got fixed from S to S', and we get the desired result. ■

    Thus, if we have a₁, bᵢ, …, bⱼ, a₂ with each aS \ U and each bUS and a₁ > a₂ and we swap a₁ and a₂, getting a₂, bᵢ, …, bⱼ, a₁, the inversion count is lower. Since such swaps only rearrange elements of S \ U and not those of US, any solution which has zero inversions on US and (subject to that) a minimal number of inversions on S \ U must make all such swaps.

    Ergo: the elements of S \ U must occur in order, and thus the solution is an interleaving of US and S \ U.

提交回复
热议问题