NlogN中最长的递增子序列长度。[了解算法]

随机

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

算法:我理解算法,如下所述:http : //www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/

我不明白的是以下代码中存储在尾部的内容。

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。但是尾部将存储2,3,6,8,10,13。

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

戴尔

tail[i]是length的递增子序列(IS)的最小最终值i+1

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

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

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

之后9我们的算法的步骤tail如下所示:
尾巴= 2,3,6,8,10,13,...

什么tail[2]意思 这意味着长度最好的IS以3结尾tail[2]并且我们可以建立一个长度为IS的IS,其长度4大于tail[2]

tail[0] = 2IS length = 12,5,3,7,11,8,10,13,6
tail[1] = 3IS length = 22,5,3,7,11,8,10,13,6
tail[2] = 6IS length = 32,5,3,7,11, 8,10,13,6
tail[3] = 8IS length = 42,5,37,11,8,10,13,6
tail[4] = 10IS length = 52,5,37,11,810,13,6
tail[5] = 13IS length = 62,5 ,37,11,81013,6

此演示文稿使您可以使用二进制搜索(请注意,tail始终对的定义部分进行排序)来更新tail并在算法末尾查找结果。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章