回答

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)很容易。我們需要的是一個數據結構,它可以讓我們高效地求和和更新一個範圍內的元素:segment trees,binary indexed trees

+0

'O(n * n * k)'方法肯定會得到超過時間限制(TLE)。相反,我們應該使用BIT或Segment Tree來加快速度。 – 2013-02-25 07:01:01

+0

@mostafiz - 是的,這就是第二種方法。 – IVlad 2013-02-25 09:43:33

+1

你是什麼意思「num [i] =以i結尾的子序列(元素,這次不是索引)有一定的長度」,如果我們在不同索引處有類似的元素會怎樣? – bicepjai 2014-12-08 01:24:42

相關問題