6

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

实际上这是Spoj Online Judge的问题

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

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

所以,答案是2

4

1 回答 1

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可以达到10000. k足够小,所以我们应该尝试找到一种方法来摆脱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)很容易地减少它。我们所需要的只是一个数据结构,它可以让我们有效地求和和更新一个范围内的元素:段树二叉索引树等。

于 2013-02-25T00:25:43.637 回答