partition a sequence of 2n real numbers so that

后端 未结 3 2057
深忆病人
深忆病人 2021-02-15 06:07

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

3条回答
  •  遇见更好的自我
    2021-02-15 06:27

    Given the input array

    x0 x1 x2 ... x2n

    use merge sort to sort it in O( n log n) time to produce a sorted list

    xa0 xa1 ... xa2n

    where the indices ai indicate the permutation that you have performed on the initial list to obtain the second list.

    I claim then that the pairing that produces the minimum maximum sum over all pairings is the following pairing:

    (xai, xa2n-i) for i = 0, 1, ..., n. That is, you group the highest valued number with the lowest valued number available.

    Proof

    Proceed by induction, for the case 2n=2 this is obvious.

    Without loss of generality consider that the input is a list of sorted numbers (since if it is not then sort them)

    x0 x1 x2 ... x2n.

    Consider the pairing of x2n with any number, then clearly the minmum sum of this pairing is achieved with (x2n, x0).

    Now consider the pairing of x2n-1, either (x2n,x0),(x2n-1,x1) is the pairings that produce the minumim max sum, or (x2n,x1),(x2n-1,x0) is, or both are. In the latter case our choice doesn't matter. In the seconds to last case, this is impossible (think about it.) In the general case if we proceed inductively by this process, when we are looking for a pair for x2n-k, xk is the lowest unused value that we can pair up with, however; suppose instead we pair up xk with some other x2n-j for j < k, to try to get a lower minum sum. This is impossible as, x2n-j + xk >= x2n-k + xk, so at most we can only achieve the same minimum sum.

    This means that choosing (x2n-k,xk) gives us the minimum pairings.

提交回复
热议问题