我有以下的算法效果很好最長非降子
我試圖解釋在這裏爲自己http://nemo.la/?p=943正是在這裏解釋http://www.geeksforgeeks.org/longest-monotonically-increasing-subsequence-size-n-log-n/以及和計算器以及
我想對其進行修改,以產生最長的非單調增加子序列
爲序列30 20 20 10 10 10 10
答案應該是4: 「10 10 10 10」
但是,與nlgn版本的算法,它不工作。初始化s到包含第一元素「30」,並在第二個元素= 20。這開始是發生了什麼:
第一步:30比20。不大於或等於我們發現的最小元素大於20新的S變成了「20」
第二步:20大於或等於20。我們擴展序列和S現在包含「20 20」
第三步: 10不大於或等於20.我們發現大於10的最小元素是「20」。新的S變成「10 20」
,之後旨意永遠長不大,算法將返回2,而不是4
int height[100];
int s[100];
int binary_search(int first, int last, int x) {
int mid;
while (first < last) {
mid = (first + last)/2;
if (height[s[mid]] == x)
return mid;
else if (height[s[mid]] >= x)
last = mid;
else
first = mid + 1;
}
return first; /* or last */
}
int longest_increasing_subsequence_nlgn(int n) {
int i, k, index;
memset(s, 0, sizeof(s));
index = 1;
s[1] = 0; /* s[i] = 0 is the index of the element that ends an increasing sequence of length i = 1 */
for (i = 1; i < n; i++) {
if (height[i] >= height[s[index]]) { /* larger element, extend the sequence */
index++; /* increase the length of my subsequence */
s[index] = i; /* the current doll ends my subsequence */
}
/* else find the smallest element in s >= a[i], basically insert a[i] in s such that s stays sorted */
else {
k = binary_search(1, index, height[i]);
if (height[s[k]] >= height[i]) { /* if truly >= greater */
s[k] = i;
}
}
}
return index;
}
通過非單調遞增的序列,你的意思是非嚴格遞增?就是說,對於每一個i> j:x [i]> = x [j]'? – Anton
對不起,我很困惑:它應該是「nondecreasing」 – nevermind