首页 > 其他 > 详细

HackerRank - The Longest Common Subsequence

时间:2015-03-21 15:23:45      阅读:314      评论:0      收藏:0      [点我收藏+]

Classic DP, and requires you to track optimal path.

len1, len2 = map(int, raw_input().strip().split())

a = map(int, raw_input().strip().split())
b = map(int, raw_input().strip().split())

rec= [[(-1, (-1, -1)) for x in range(len1 + 1)] for x in range(len2 + 1)] 
dp = [[0 for x in range(len1 + 1)] for x in range(len2 + 1)] 
for i in range(1,len1 + 1):
    for j in range(1,len2 + 1):
        if i * j == 0:
            dp[j][i] = 0
            continue
        if a[i - 1] == b[j - 1]:
            dp[j][i] = dp[j - 1][i - 1] + 1
            rec[j][i] = (a[i - 1], (j - 1, i - 1))
        else:
            dp[j][i] = max(dp[j - 1][i], dp[j][i - 1])
            if dp[j - 1][i] >= dp[j][i - 1]:
                rec[j][i] = (-1, (j - 1, i))
            else:
                rec[j][i] = (-1, (j, i - 1))
#print dp[len2][len1]            

ret = []
tmp = rec[len2][len1]
while tmp[-1][-1] != -1:
    if tmp[0] != -1:
        ret.append(tmp[0])
    tmp = rec[tmp[-1][0]][tmp[-1][1]]
ret.reverse()

print ( .join(map(str, ret)))

HackerRank - The Longest Common Subsequence

原文:http://www.cnblogs.com/tonix/p/4355495.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!