题目链接:
题目大意:
给你k个序列(2=<k<=5),每个序列的长度为n(1<=n<=1000),每个序列中的数字分别为1~n,求着k个序列的最长公共子序列是多长?
解题思路:
由于每个序列的数字分别为1~n即各不相同,所以可以用pos[i][j]记录第i个序列中j的位置。
设dp[i]表示以i结尾的最长公共子序列长度,那么我们可以按顺序遍历第一个序列的位置i,
再在第一个序列中枚举位置j(j<i),然后遍历其他序列,如果对于每个序列k都满足pos[k][a[1][i]]>pos[k][a[1][j]],
那么说明a[1][i]可以接在a[1][j]后面,dp[a[1][i]]=max(dp[a[1][i],dp[a[1][j]]+1)。
这里说明一下:按顺序遍历是为了保证dp[a[1][j]]是已经求好了的,如果直接按值来遍历则会出现前面的dp值未求好的情况。
代码:
1 #include 2 #include 3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 #include 10 #include 11 #include 12 #include 13 #include