usr bin env python3 def read_ints return int value for value in input

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env python3
def read_ints():
return [int(value) for value in input().split()]
a, b = read_ints(), read_ints()
n, m = len(a), len(b)
lcs = [[0] * (m + 1) for i in range(n + 1)]
for i in range(n):
for j in range(m):
if a[i] == b[j]:
lcs[i][j] = lcs[i - 1][j - 1] + 1
else:
lcs[i][j] = max(lcs[i - 1][j], lcs[i][j - 1])
answer = []
i, j = n - 1, m - 1
while i != -1 and j != -1:
if a[i] == b[j]:
answer.append(a[i])
i -= 1
j -= 1
elif lcs[i - 1][j] > lcs[i][j - 1]:
i -= 1
else:
j -= 1
print(answer[::-1])