码迷,mamicode.com
首页 > 其他好文 > 详细

HackerRank - The Longest Common Subsequence

时间:2015-03-21 15:26:57      阅读:199      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!