这个问题已经在这里有了答案: > Find the largest possible number of people in such a tower 3个
给定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.
解决方法:
它是正确的.这是一个证明:
令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.在这种情况下,我们可以在最佳解决方案中用s1替换i1,因为s1是完成时间最短的对.因此s1,i2,…,ik仍然是最佳解决方案.
令t< = l是st!= it的第一个索引.因此,s1,s2,...,s [t-1],...是最佳解.我们可以用st代替它,因为:
> st不是最优解的前t-1个元素的一部分;
> st不是i [t 1],…,ik的一部分.如果是,那将意味着st在完成之后开始,这将与算法选择st的方式相矛盾.
因此,以这种方式继续,我们的最佳解决方案是s1,s2,…,sl,…,ik.这意味着可以在sl之后添加更多对,但这与算法的工作方式相矛盾,因此我们有l = k,并且该算法是正确的.
标签:java,algorithm
来源: https://codeday.me/bug/20191123/2063822.html