java - 对的最大长度(按升序)

标签 java algorithm

<分区>

给定 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

最佳答案

这是正确的。这是一个证明:

s1, s2, ..., sl是你的算法找到的对和i1, i2, ..., ik是最优解。

我们有:

l == k => your algorithm is obviously correct, since it's clear that
          it doesn't produce invalid solutions;

l > k => this would contradict our hypothesis that i1, ..., ik is optimal,
         so it makes no sense to bother with this;

l < k => this would mean that your algorithm is wrong. 
         Let's assume this is the case.

假设i1 != s1 .在这种情况下,我们可以替换 i1s1在最佳解决方案中,因为 s1是完成时间最短的一对。所以s1, i2, ..., ik仍然是最优解。

t <= lst != it 的第一个索引.因此,s1, s2, ..., s[t-1], it, ...是最优解。我们可以替换 itst因为:

  • st不是第一个 t-1 的一部分最佳解决方案的要素;
  • st不属于 i[t+1], ..., ik .如果是,那就意味着 stit 之后开始完成,这将与算法选择 st 的方式相矛盾.

因此,继续以这种方式,我们的最佳解决方案是 s1, s2, ..., sl, ..., ik .这意味着可以在 sl 之后添加更多对, 但这与算法的工作方式相矛盾,所以我们有 l = k , 算法正确。

关于java - 对的最大长度(按升序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18018911/

相关文章:

java - 编译失败子包不存在

Java,用Runtime.exec()继承类路径

regex - 网站智能数据提取算法

java - 损坏的插入排序

python - 在 Python 中确定嵌套元组的嵌套级别的简单方法

java - 如何从外部访问 docker 中的 JMX 接口(interface)?

java - 在 GET Rest 资源中发送 JSON -curl 和代码具有不同的行为

java - 无法在 Eclipse 中运行 Spring Boot + JavaFX

java - 将字符串和字节存储在单个 int 值中

c++ - 如何仅使用第二个值从集合中查找对?