长度为k的递增子序列的个数

Number of Increasing Subsequences of length k

本文关键字:      更新时间:2023-10-16

我正试图理解该算法,该算法在时间O(n K log(n))中给我数组中长度为K的递增子序列的数量。我知道如何用O(k*n^2)算法解决同样的问题。我查了一下,发现这个解决方案使用BIT (Fenwick Tree)和DP。我也发现了一些代码,但我无法理解它。

以下是我访问过的一些有帮助的链接。

Here in SO
Topcoder论坛
随机网页

如果有人能帮助我理解这个算法,我将非常感激。

我从这里复制了我的算法,其中解释了它的逻辑:

dp[i, j] = same as before num[i] = how many subsequences that end with i (element, not index this time) 
         have a certain length
for i = 1 to n do   dp[i, 1] = 1
for p = 2 to k do // for each length this time   num = {0}
  for i = 2 to n do
    // note: dp[1, p > 1] = 0 
    // how many that end with the previous element
    // have length p - 1
    num[ array[i - 1] ] += dp[i - 1, p - 1] *1*   
    // append the current element to all those smaller than it
    // that end an increasing subsequence of length p - 1,
    // creating an increasing subsequence of length p
    for j = 1 to array[i] - 1 do *2*       
      dp[i, p] += num[j]

您可以使用段树或二叉索引树来优化*1**2*。这些将用于有效地处理num数组上的以下操作:

  • 给定(x, v),添加vnum[x](与*1*相关);
  • 给定x,求num[1] + num[2] + ... + num[x]的和(与*2*相关)。

对于这两种数据结构来说,这些都是微不足道的问题。

注意:这将具有复杂性O(n*k*log S),其中S是数组中值的上界。这可能足够好,也可能不够好。为了使它成为O(n*k*log n),您需要在运行上述算法之前对数组的值进行规范化。规范化意味着将所有数组值转换为小于或等于n的值。所以这:

5235 223 1000 40 40

就变成:

4 2 3 1 1

这可以通过排序(保留原始索引)来完成。

相关文章:
  • 没有找到相关文章