在最长公共递增序列问题中没有得到预期的输出

问题描述 投票:0回答:0
def LCIS(A, B):
n = len(A)
m = len(B)

# Initialize the dynamic programming table
dp = [[0] * (m + 1) for _ in range(n + 1)]

# Fill the table
for i in range(1, n + 1):
    max_len = 0
    for j in range(1, m + 1):
        if A[i-1] > B[j-1]:
            dp[i][j] = dp[i-1][j]
        else:
            dp[i][j] = max_len + 1
            if A[i-1] == B[j-1]:
                max_len = max(max_len, dp[i-1][j-1])

 # Find the maximum value in the table
 max_val = 0
 for i in range(1, n + 1):
    for j in range(1, m + 1):
        if dp[i][j] > max_val:
            max_val = dp[i][j]

return max_val

# Read the input from file named my_own_test
with open('A2Q2.in', 'r') as f:                
lines = f.readlines()

t = int(lines[0])

for i in range(1, len(lines), 2):
A = list(map(lambda x: int(x, 16), lines[i].split()))
B = list(map(lambda x: int(x, 16), lines[i+1].split()))

# Compute and print the LCIS of A and B
print(LCIS(A, B))

给定两个序列 A = {a1, a2, …, am} 和 B = {b1, b2, …, bn},序列 C = {c1, c2, …, ck} 称为 A 和B,如果 (i) 存在两个严格递增的函数 f 和 g(意思是 f(x1) < f(x2) if x1 < x2), such that ci = af(i) = bg(i) for all 1 ≤ i ≤ k ; and (ii) the sequence C is an increasing sequence, i.e., c1 < c2 < … < ck. In simple words, the sequence C must be a subsequence of A and a subsequence of B at the same time (not necessarily continuous, e.g., it is possible that c1 = a1, c2 = a3, c3 = a6, …), and C itself forms an increasing sequence. There could be many common increasing subsequences between A and B, however, there are longest subsequences among them. In this question, you are to compute the length of longest common increasing subsequences with dynamic programming.

我正在 LCIS 函数中实现一个算法。

测试输入以序列对的数量开始。每个序列由一行描述,并包含 1 到 224-1 之间的十六进制正整数列表。每个序列的长度记为n,1≤n≤5000。对于每对序列,输出最长公共递增子序列的长度。

这是示例输入:

3
6186ba 5b6eee 46b349 a4bcb9 1f0562 d3161e 87e6bf 12c6d4 299675 ea50c0 42e22a
46b349 2d110b 4158e6 715ae5 2eff32 87e6bf 21a447 12b23b 55e5f6 8d20e2 ad057a ea50c0 f4c9c0 3dde52 ec2c78
d6cd72 a0eb35 739595 438f9 f5a133 f5168d 6ec390 52167 eaf15b f28f87 7c6a47 a55672 9c5154 8ad488
d08d43 8f4a80 5dc1ef bcc37f 739595 110d0c fc4280 fcbcf6 58bdae f5168d 9a344 eaf15b 16b458 23526f a55672 7a50c7
4425e0 1bc553 2572eb 387171 12a9a4 72957e dc6dc 50c7bf b6f3af 596b53 315c94 2c7c1e 70325a 5022f6 319431
387171 a07f9c 71ff0f 12a9a4 20d008 dc6dc 41b633 eab224 4d9f4f 4fedb9 50c7bf d5e910 a2d3d0 ce4cf8 6867b9 70325a c9a68f 9f8d26 689102 4b407 1c3728

预期输出为:

3
2
3

但我得到的是:

2
2
4

任何人都可以帮助确定上面的代码有什么问题吗?

python algorithm data-structures dynamic-programming
© www.soinside.com 2019 - 2024. All rights reserved.