partition a sequence of 2n real numbers so that

后端 未结 1 1821
长情又很酷
长情又很酷 2021-02-15 05:59

I\'m currently reading The Algorithm Design Manual and I\'m stuck on this exercise.


Take a sequence of 2n real numbers as input. Design an O(n log n) algorithm tha

相关标签:
1条回答
  • 2021-02-15 06:25

    The algorithm works because when x0, x1, ... x2n-1 is the sorted list, there is always an optimal solution that contains (x0, x2n-1).

    Proof:

    Consider any optimal solution which does not contain (x0, x2n-1). It must contain pairs (x0, xa) and (xb, x2n-1) with x0 ≤ xa ≤ x2n-1 and x0 ≤ xb ≤ x2n-1. Remove those pairs from the solution, and in their place put (x0, x2n-1) and (xa, xb). Could the presence of either new pair have "damaged" the solution? The pair (x0, x2n-1) could not have, since its sum is less than or equal to the sum of (xb, x2n-1) which was a member of the original, optimal solution. Neither again could (xa, xb) have caused damage, since its sum is less than or equal to the sum of (xb, x2n-1), which was a member of the same solution. We have constructed an optimal solution which does contain (x0, x2n-1).

    Thus the algorithm you give never forecloses the possibility of finding an optimal solution at any step, and when there are only two values left to pair they must be paired together.

    0 讨论(0)
提交回复
热议问题