<分区>
给定 n 对数字,第一个数字总是小于第二个数字。当且仅当 b <= c 时,一对 (c, d) 可以跟在一对 (a, b) 之后。对链可以以这种方式形成。找到可以从给定的一组对中形成的最长链。
例如{ (1,2), (3,4), (5,7), (9,10), (7,9), (8,9), (0,6)
所以输出应该是:{(1,2), (3,4), (5,7), (8,9), (9,10)}
我的算法如下:
1. Sort the list according to the 2nd number of elements
i.e.`{ (1,2), (3,4), (0,6), (5,7), (7,9), (8,9), (9,10) }`
2. choose the first element from the list i.e. `(1,2)`
3. for each element e in the list left
4. choose this element e if the first number of the element is greater than the 2nd number of the previous element. i.e. after `(1,2)` choose `(3,4)` because `3 > 2.`
在上述算法之后,您将得到输出为 {(1,2), (3,4), (5,7), (8,9), (9,10)}
.
请让我知道算法的正确性。谢谢。
编辑:
更直观的正确性证明:
Proof: The only way to include more pairs in the chain is to replace a pair with one with a smaller Y value, to allow for the next pair to have a smaller X value, potentially fitting another pair where it couldn't fit before. If you replace a pair with one with the same Y value, you gain nothing. If the replacement has a larger Y value, all you've done is potentially block some pairs that would've fit before.
Because the pairs have been sorted by Y values, you will never find a replacement with a smaller Y. Looking "forward" in the sorted pairs, they will all have the same or greater Y value. Looking "backward", any that were eliminated from the chain initially were because the X value wasn't high enough, which will still be the case.
这取自here