如何使用二进制索引树(BIT)查找一定长度的增加子序列的总数

时间:2013-02-24 22:45:33

标签: algorithm data-structures sequence fenwick-tree binary-indexed-tree

如何使用二进制索引树(BIT)找到一定长度的增加子序列的总数?

实际上这是来自Spoj Online Judge

的问题

示例
假设我有一个数组1,2,2,10

长度为3的增加的子序列是1,2,41,3,4

所以答案是2

1 个答案:

答案 0 :(得分:10)

让:

dp[i, j] = number of increasing subsequences of length j that end at i

一个简单的解决方案是O(n^2 * k)

for i = 1 to n do
  dp[i, 1] = 1

for i = 1 to n do
  for j = 1 to i - 1 do
    if array[i] > array[j]
      for p = 2 to k do
        dp[i, p] += dp[j, p - 1]

答案是dp[1, k] + dp[2, k] + ... + dp[n, k]

现在,这可行,但对于给定的约束效率不高,因为n可以达到10000k足够小,因此我们应该尝试找到摆脱n的方法。

让我们尝试另一种方法。我们还有S - 数组中值的上限。让我们尝试找一个与此相关的算法。

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]   

    // 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        
      dp[i, p] += num[j]

这具有复杂性O(n * k * S),但我们可以非常轻松地将其缩减为O(n * k * log S)。我们所需要的只是一个数据结构,它可以让我们有效地汇总和更新范围内的元素:segment treesbinary indexed trees等。