【问题标题】:Longest Increasing Subsequence optimization最长递增子序列优化
【发布时间】:2016-07-02 13:12:07
【问题描述】:

最长递增子序列问题是找到给定序列的子序列,其中子序列的元素按排序顺序排列,并且子序列尽可能长。

这是我的 O(n^2) 方法,对于长输入运行非常慢:

N = int(input())

lst = []
for i in range(N):
    lst.append(input())

count = [1] * N

for i in range(1, len(lst)):
    for j in range(i):
        if(int(lst[j]) < int(lst[i])):
            k = int(count[j]) + 1
            if (k > int(count[i])):
                count[i] = k
count.sort()
print(count[-1])

谁能告诉我如何在 O(n*log n) 时间内完成?

【问题讨论】:

标签: python dynamic-programming subsequence


【解决方案1】:

cmets 中提到了大量资源;如果你还想要一段python代码,我这里已经写好了。

在这个算法中,对于所有L &lt; N,我们会跟踪输入中的值,这些值表示当前长度为L的最长递增子序列的端点。

longest_sequence_values 存储这些值。例如,longest_sequence_values[3] 是输入中长度为 3 的最长递增子序列结束处的值。

请注意,longest_sequence_values 始终是非递减的,这允许我们在尝试构建新的最长递增子序列时执行二分查找。这是因为如果i &lt; j,那么长度为i 的子序列的端点不能大于长度为j 的子序列的端点。

longest_current_sequence 是迄今为止发现的最长子序列的长度。我们需要这个值来指定二分查找的范围。也代表了最后的答案。

from math import ceil
N = int(input())

input_vals = []
for i in range(N):
    input_vals.append(input())

longest_sequence_values = [None] * (N+1)
longest_current_sequence = 0

for i in range(N):
    # binary search starts here
    # this gives us the log(N) factor
    lo = 1
    hi = longest_current_sequence
    while lo <= hi:
        mid = int(ceil((lo+hi)/2))
        if longest_sequence_values[mid] <= input_vals[i]:
            lo = mid + 1
        else:
            hi = mid - 1

    # lo will be length of the longest sequence ending at input_vals[i]
    longest_len_here = lo
    # We have a new lis of length longest_len_here ending at index i
    # Note that before we perform the following substitutions,
    # longest_sequence_values[longest_len_here] >= input_vals[i]
    # This means that the new endpoint of the lis of length longest_len_here
    # is <= to the old endpoint.
    # This point is essential in keeping the result optimal
    longest_sequence_values[longest_len_here] = input_vals[i]

    if longest_len_here > longest_current_sequence:
        longest_current_sequence = longest_len_here

print longest_current_sequence

【讨论】:

  • 您的代码运行完美。这是我的代码,它对某些输入工作正常,但对某些输入却不是。它有一些错误,你能告诉我我在哪里做错了吗? paste.ofcode.org/WFqZYpE2e2av4KwhpfSV74
  • @Atinesh 你能发布一些失败的输入吗?理想情况下,tailTable 应该处理[1, N] 范围内的索引,而不是[0, N]。这是因为索引表示大小为1..N 的长度,这样会更直观。您的 binary_search 方法看起来很弱。出于某种原因,起始范围是[-1, N-1]。二进制搜索用于使用属性将排序范围分为两部分。在这种情况下,该属性是“最大的j &lt; len 这样tailTable[j] &lt;= key”。确保是这种情况。
  • 实际上,我在Hacker Rank 上尝试了此代码,他们已经在 9 个测试用例中对其进行了测试,其中只有 2 个成功。这是测试用例Input:paste.ofcode.org/MTCs4irbBFNNndgAGf3yEkExpected Output:185
  • 我无法使用该大小的测试输入进行任何有用的推断。如果可以的话,找一个你的代码中断的小测试用例并发布它。不过,我很确定这是二进制搜索。将您的tailTable 范围从[0, N-1] 更改为[1, N],研究我使用的二进制搜索,你应该很高兴。
  • @Atinesh 我刚刚在你提供的输入上运行了你的代码,它给出了 185,你说这是预期的输出......
猜你喜欢
  • 2013-07-03
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
  • 2014-07-07
  • 2018-11-01
相关资源
最近更新 更多