最長的雙調子序列
如果一個序列先遞增後遞減,則稱之為雙調子序列。在這個問題中,給定一個全為正整數的陣列。我們必須找到一個先遞增後遞減的子序列。
為了解決這個問題,我們將定義兩個子序列,它們是最長遞增子序列和最長遞減子序列。LIS 陣列將儲存以陣列 [i] 結尾的遞增子序列的長度。LDS 陣列將儲存從陣列 [i] 開始的遞減子序列的長度。使用這兩個陣列,我們可以得到最長雙調子序列的長度。
輸入和輸出
Input: A sequence of numbers. {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15} Output: The longest bitonic subsequence length. Here it is 7.
演算法
longBitonicSub(array, size)
輸入:陣列、陣列的長度。
輸出 − 最長雙調子序列的最大長度。
Begin define incSubSeq of size same as the array size initially fill all entries to 1 for incSubSeq for i := 1 to size -1, do for j := 0 to i-1, do if array[i] > array[j] and incSubSeq[i] < incSubSum[j] + 1, then incSubSum[i] := incSubSum[j] + 1 done done define decSubSeq of size same as the array size. initially fill all entries to 1 for incSubSeq for i := size - 2 down to 0, do for j := size - 1 down to i+1, do if array[i] > array[j] and decSubSeq[i] < decSubSum[j] + 1, then decSubSeq [i] := decSubSeq [j] + 1 done done max := incSubSeq[0] + decSubSeq[0] – 1 for i := 1 to size, do if incSubSeq[i] + decSubSeq[i] – 1 > max, then max := incSubSeq[i] + decSubSeq[i] – 1 done return max End
示例
#include<iostream> using namespace std; int longBitonicSub( int arr[], int size ) { int *increasingSubSeq = new int[size]; //create increasing sub sequence array for (int i = 0; i < size; i++) increasingSubSeq[i] = 1; //set all values to 1 for (int i = 1; i < size; i++) //compute values from left ot right for (int j = 0; j < i; j++) if (arr[i] > arr[j] && increasingSubSeq[i] < increasingSubSeq[j] + 1) increasingSubSeq[i] = increasingSubSeq[j] + 1; int *decreasingSubSeq = new int [size]; //create decreasing sub sequence array for (int i = 0; i < size; i++) decreasingSubSeq[i] = 1; //set all values to 1 for (int i = size-2; i >= 0; i--) //compute values from left ot right for (int j = size-1; j > i; j--) if (arr[i] > arr[j] && decreasingSubSeq[i] < decreasingSubSeq[j] + 1) decreasingSubSeq[i] = decreasingSubSeq[j] + 1; int max = increasingSubSeq[0] + decreasingSubSeq[0] - 1; for (int i = 1; i < size; i++) //find max length if (increasingSubSeq[i] + decreasingSubSeq[i] - 1 > max) max = increasingSubSeq[i] + decreasingSubSeq[i] - 1; return max; } int main() { int arr[] = {0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}; int n = 16; cout << "Length of longest bitonic subsequence is " << longBitonicSub(arr, n); }
輸出
Length of longest bitonic subsequence is 7
廣告