Tony's Log

Algorithms, Distributed System, Machine Learning

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

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)))
posted on 2015-03-21 13:45  Tonix  阅读(164)  评论(0编辑  收藏  举报