私はうまく機能する次のアルゴリズムを持っています
ここで自分で説明しようとしました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 バージョンのアルゴリズムでは機能しません。最初の要素「30」を含むように s を初期化し、2 番目の要素 = 20 から開始します。次のようになります。
最初のステップ: 30 は 20 以下です。20 より大きい最小の要素を見つけます。新しい s は「20」になります。
2 番目のステップ: 20 は 20 以上です。シーケンスを拡張すると、s には "20 20" が含まれます。
3 番目のステップ: 10 は 20 以下です。「20」である 10 より大きい最小の要素を見つけます。新しい s は「10 20」になります
その後、s は決して大きくならず、アルゴリズムは 4 ではなく 2 を返します。
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;
}