How to find the total number of Increasing sub-sequences of certain length with Binary Index Tree(BIT)
Asked Answered
P

1

7

How can I find the total number of Increasing sub-sequences of certain length with Binary Index Tree(BIT)?

Actually this is a problem from Spoj Online Judge

Example
Suppose I have an array 1,2,2,10

The increasing sub-sequences of length 3 are 1,2,4 and 1,3,4

So, the answer is 2.

Paterfamilias answered 24/2, 2013 at 22:45 Comment(0)
D
10

Let:

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

An easy solution is in 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]

The answer is dp[1, k] + dp[2, k] + ... + dp[n, k].

Now, this works, but it is inefficient for your given constraints, since n can go up to 10000. k is small enough, so we should try to find a way to get rid of an n.

Let's try another approach. We also have S - the upper bound on the values in our array. Let's try to find an algorithm in relation to this.

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]

This has complexity O(n * k * S), but we can reduce it to O(n * k * log S) quite easily. All we need is a data structure that lets us efficiently sum and update elements in a range: segment trees, binary indexed trees etc.

Divorcee answered 25/2, 2013 at 0:25 Comment(6)
O(n*n*k) approach will certainly get Time Limit Exceeded(TLE). Rather we should use BIT or Segment Tree to make it faster.Paterfamilias
@mostafiz - yes, that's what the second approach is for.Divorcee
what do you mean by "num[i] = how many subsequences that end with i (element, not index this time) have a certain length", what if we have similar elements at different indices ?Dc
@Dc - then you update num[i] that many times, when you reach each one. Like in the pseudocode.Divorcee
what is k? Can u please elaborate?Radiogram
also not sure of what n isRadiogram

© 2022 - 2024 — McMap. All rights reserved.