[英]Longest Increasing Cyclic Subsequence
我有一個代碼,可以找到最長的遞增子序列,但是我想擴展它以允許環繞。 例如,對於序列(4,5,6,1,2,3),最長的循環子序列是(1,2,3,4,5,6),因為一旦達到3,我們就可以回到起點的順序(我們只能執行一次。)有人可以幫助我嗎?
這是代碼:
def longest_increasing_subsequence(X):
N = len(X)
P = [0] * N
M = [0] * (N+1)
L = 0
for i in range(N):
lo = 1
hi = L
while lo <= hi:
mid = (lo+hi)//2
if (X[M[mid]] < X[i]):
lo = mid+1
else:
hi = mid-1
newL = lo
P[i] = M[newL-1]
M[newL] = i
if (newL > L):
L = newL
S = []
k = M[L]
for i in range(L-1, -1, -1):
S.append(X[k])
k = P[k]
return len(S[::-1])
將序列連接到其末尾,然后在其上運行算法。
只需檢查每個班次從函數返回的值:
max_increasing=longest_increasing_subsequence(X)
for i in range(len(X)-1):
X=X.append(X.pop(0)) #shift X by 1
if longest_increasing_subsequence(X)>max_increasing:
max_increasing=longest_increasing_subsequence(X)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.