蒟蒻LCS 50分 求助

P1439 【模板】最长公共子序列

wzqqqqq @ 2022-04-27 09:46:16

n = int(input())
ans1 = list(map(int,input().split()))
ans2 = list(map(int,input().split()))
dp = [[0 for i in range(len(ans1))] for  j in range(len(ans2))]
for i in range(len(dp[0])):
    if ans1[i] == ans2[0]:
        dp[0][i] = dp[0][i-1] + 1
    else:
        dp[0][i] = dp[0][i - 1]
for j in range(len(dp)):
    if ans2[j] == ans1[0]:
        dp[j][0] = dp[j-1][0] + 1
    else:
        dp[j][0] = dp[j - 1][0]
for i in range(1,len(dp)):
    for j in range(1, len(dp[0])):
        if ans1[j] == ans2[i]:
            dp[i][j] =max(dp[i-1][j]+1,dp[i][j-1]+1)
        else:
            dp[i][j] = max(dp[i-1][j],dp[i][j-1])
print(dp[-1][-1])

by Hisaishi_Kanade @ 2022-04-27 09:48:29

@wzqqqqq 建议看题解,此题O(N^2)显然不行


by NastiY_iN_saNitY @ 2022-04-27 09:50:17

@wzqqqqq 看完数据范围再来求助啊……


by NastiY_iN_saNitY @ 2022-04-27 09:52:34


by wzqqqqq @ 2022-04-27 10:38:13

所以怎么压缩维度呢


|