您的位置:首页 > 其它

最长非降 nlogn 带路径标记

2014-09-22 12:05 218 查看
http://en.wikipedia.org/wiki/Longest_increasing_subsequence 本文来自wiki

X[i]就是表示原始序列

M[j] 存的是长度为j 的子序列,最后一个数的位置在M[j]

P[k] 表示第k个元素的决策前驱是p[k]

X[M[1]] X[M[2]] X[M[L]] 是一个单调队列,这个实现有点巧,用M数组来记录单调队列元素的下标。

P = array of length N
M = array of length N + 1

L = 0
for i in range 0 to N-1:
// Binary search for the largest positive j ≤ L
// such that X[M[j]] < X[i]
lo = 1
hi = L
while lo ≤ hi:
mid = (lo+hi)/2
if X[M[mid]] < X[i]:
lo = mid+1
else:
hi = mid-1

// After searching, lo is 1 greater than the
// length of the longest prefix of X[i]
newL = lo

// The predecessor of X[i] is the last index of
// the subsequence of length newL-1
P[i] = M[newL-1]

if newL > L:
// If we found a subsequence longer than any we've
// found yet, update M and L
M[newL] = i
L = newL
else if X[i] < X[M[newL]]:
// If we found a smaller last value for the
// subsequence of length newL, only update M
M[newL] = i

// Reconstruct the longest increasing subsequence
S = array of length L
k = M[L]
for i in range L-1 to 0:
S[i] = X[k]
k = P[k]

return S


Because the algorithm performs a single binary search per sequence element, its total time can be expressed using Big
O notation as O(n log n). Fredman
(1975) discusses a variant of this algorithm, which he credits to Donald
Knuth; in the variant that he studies, the algorithm tests whether each value X[i]
can be used to extend the current longest increasing sequence, in constant time, prior to doing the binary search. With this modification,
the algorithm uses at mostn log2 n − n log2log2 n +
O(n) comparisons in the worst case, which is optimal for a comparison-based algorithm up to the constant factor in the O(n)
term.[5]


Length bounds[edit]

According to the Erdős–Szekeres theorem, any sequence
of n2+1 distinct integers has either an increasing or a decreasing subsequence of length n + 1.[6][7] For
inputs in which each permutation of the input is equally likely, the expected length of the longest increasing subsequence is approximately 2√n. [8] In
the limit as n approaches infinity, the length of the longest increasing subsequence of a randomly permuted sequence of n items has a distribution approaching theTracy–Widom
distribution, the distribution of the largest eigenvalue of a random matrix in the Gaussian
unitary ensemble.[9]

PS:

Szekeres
theorem,

For given r, s they
showed that any sequence of length at least (r − 1)(s − 1) + 1
contains a monotonically increasing subsequence of length r or a
monotonically decreasing subsequence of length s.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: