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



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

事实上,这是斯波特在线法官的一个问题

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

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

因此,答案是2

设:

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)。我们所需要的只是一个数据结构,它可以让我们有效地求和和和更新一个范围内的元素:分段树、二进制索引树等。

相关内容

  • 没有找到相关文章

最新更新