【问题标题】:Longest Increasing subsequence length in NlogN.[Understanding the Algo]NlogN 中最长的递增子序列长度。[理解算法]
【发布时间】:2017-12-10 08:15:36
【问题描述】:

问题陈述:目的是在nlogn时间内找到最长的递增子序列(不连续)。

算法:我理解这里解释的算法: http://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/.

我不明白的是在下面的代码中,tail 中存储了什么。

int LongestIncreasingSubsequenceLength(std::vector<int> &v) {
if (v.size() == 0)
    return 0;

std::vector<int> tail(v.size(), 0);
int length = 1; // always points empty slot in tail

tail[0] = v[0];
for (size_t i = 1; i < v.size(); i++) {
    if (v[i] < tail[0])
        // new smallest value
        tail[0] = v[i];
    else if (v[i] > tail[length-1])
        // v[i] extends largest subsequence
        tail[length++] = v[i];
    else
        // v[i] will become end candidate of an existing subsequence or
        // Throw away larger elements in all LIS, to make room for upcoming grater elements than v[i]
        // (and also, v[i] would have already appeared in one of LIS, identify the location and replace it)
        tail[CeilIndex(tail, -1, length-1, v[i])] = v[i];
}

return length;
}

例如,如果输入是 {2,5,3,,11,8,10,13,6}, 该代码给出了正确的长度为 6。 但是tail会存储2,3,6,8,10,13。

所以我想了解tail中存储了什么?这将有助于我理解这个算法的正确性。

【问题讨论】:

    标签: algorithm sorting binary-search correctness


    【解决方案1】:

    tail[i] 是长度为i+1 的递增子序列 (IS) 的最小结束值。

    这就是为什么tail[0] 是“最小值”以及为什么当当前值大于当前最长序列的结束值时我们可以增加 LIS (length++) 的值。

    假设您的示例是输入的起始值:

    输入 = 2, 5, 3, 7, 11, 8, 10, 13, 6, ...

    在我们的算法tail9 步骤之后看起来像这样:
    尾巴 = 2, 3, 6, 8, 10, 13, ...

    tail[2] 是什么意思?这意味着长度为3 的最佳IS 以tail[2] 结尾。我们可以构建一个长度为4 的IS,将其扩展为大于tail[2] 的数字。

    tail[0] = 2, IS length = 1: 2, 5, 3, 7, 11, 8, 10, 13, 6
    tail[1] = 3, @ 987654335@: 2, 5, 3, 7, 11, 8, 10, 13, 6
    tail[2] = 6, @987654337 @:2、5、3、7、11、8、10、13、6
    tail[3] = 8IS length = 42、5、37、11、8 , 10, 13, 6
    tail[4] = 10,IS length = 5: 2, 5, 3, 7, 11、810、13、6
    tail[5] = 13,IS length = 6:2, 5、37、11、81013,6

    此演示文稿允许您使用二分搜索(注意 tail 的定义部分始终排序)来更新 tail 并在算法结束时找到结果。

    【讨论】:

    • 感谢您的回复。你能解释一下最低终值吗
    • @NikhilSaxena, min(last element of the increasing subsequences with length i)
    【解决方案2】:

    Tail 搜索最长递增子序列 (LIS)。

    它将按照您提供并声称已理解的链接中给出的解释进行自我更新。检查示例。

    您希望尾部的第一个元素处的最小值,这解释了第一个 if 语句。

    第二个 if 语句允许 LIS 增长,因为我们想要最大化它的长度。

    【讨论】:

    • 2,3,6,8,10,13 :它不是 LIS。 6 在输入的最后一个
    猜你喜欢
    • 2011-09-02
    • 2014-01-02
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多