Skip to content

Commit c40dd7f

Browse files
committed
Fix bug in LongestIncreasingSubsequence
The `dad` array was not being updated properly. E.g., running LongestIncreasingSubsequence on {5,6,2,3} would return {5,3}. Fixes #8
1 parent 095676e commit c40dd7f

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

code/LongestIncreasingSubsequence.cc

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// Given a list of numbers of length n, this routine extracts a
1+
// Given a list of numbers of length n, this routine extracts a
22
// longest increasing subsequence.
33
//
44
// Running time: O(n log n)
@@ -21,7 +21,7 @@ typedef vector<PII> VPII;
2121
VI LongestIncreasingSubsequence(VI v) {
2222
VPII best;
2323
VI dad(v.size(), -1);
24-
24+
2525
for (int i = 0; i < v.size(); i++) {
2626
#ifdef STRICTLY_INCREASNG
2727
PII item = make_pair(v[i], 0);
@@ -35,11 +35,11 @@ VI LongestIncreasingSubsequence(VI v) {
3535
dad[i] = (best.size() == 0 ? -1 : best.back().second);
3636
best.push_back(item);
3737
} else {
38-
dad[i] = dad[it->second];
38+
dad[i] = it == best.begin() ? -1 : prev(it)->second;
3939
*it = item;
4040
}
4141
}
42-
42+
4343
VI ret;
4444
for (int i = best.back().second; i >= 0; i = dad[i])
4545
ret.push_back(v[i]);

0 commit comments

Comments
 (0)