def createSub lcs, x, y, i, j
if i == 0 or j == 0
return
end
if x[ i ].to_i == y[ j ].to_i
createSub(lcs, x, y, i - 1, j - 1)
print x[i], " "
else
if lcs[ i ][ j - 1] < lcs[ i - 1 ][ j ]
createSub(lcs, x, y, i - 1, j)
else
createSub(lcs, x, y, i, j - 1)
end
end
end
def max a,b
if a > b
return a
else
return b
end
end
def main
x = [0, 1, 7, 3, 5, 8]
y = [0, 7, 5, 8, 1]
n = x.length() - 1
m = y.length() - 1
lcs = Array.new(n+1){Array.new(m+1,0)}
1.upto(n) {
|i|
1.upto(m) {
|j|
if x[i].to_i == y[j].to_i
lcs[i][j] = 1 + lcs[i-1][j-1].to_i
else
lcs[i][j] = max(lcs[i][j-1].to_i, lcs[i-1][j].to_i)
end
}
}
p lcs[n][m]
createSub(lcs, x, y, n, m)
end
main
ZGVmIGNyZWF0ZVN1YiBsY3MsIHgsIHksIGksIGoKICAgICAKICAgICBpZiBpID09IDAgb3IgaiA9PSAwICAKICAgICAgIAogICAgCXJldHVybgoKICAgICBlbmQJCiAgICAKICAgIAlpZiB4WyBpIF0udG9faSA9PSB5WyBqIF0udG9faQogICAgICAgICAgIAogICAgCSAgIGNyZWF0ZVN1YihsY3MsIHgsIHksIGkgLSAxLCBqIC0gMSkKCiAgICAJICAgcHJpbnQgeFtpXSwgIiAiIAkgICAKCiAgICAJZWxzZQoKICAgIAkJaWYgbGNzWyBpIF1bIGogLSAxXSA8IGxjc1sgaSAtIDEgXVsgaiBdCgogICAgCQkJY3JlYXRlU3ViKGxjcywgeCwgeSwgaSAtIDEsIGopCgogICAgCQllbHNlCgogICAgICAgICAgICAgICAgY3JlYXRlU3ViKGxjcywgeCwgeSwgaSwgaiAtIDEpCgogICAgCSAgICBlbmQJCgogICAgCWVuZAkgICAgCmVuZAoKZGVmIG1heCBhLGIKCiAgICBpZiBhID4gYgogICAgCXJldHVybiBhCiAgICBlbHNlCiAgICAJcmV0dXJuIGIKICAgIGVuZCAJCmVuZAkKCmRlZiBtYWluICAgIAoKCXggPSBbMCwgMSwgNywgMywgNSwgOF0JCiAgICB5ID0gWzAsIDcsIDUsIDgsIDFdCgogICAgbiA9IHgubGVuZ3RoKCkgLSAxCiAgICBtID0geS5sZW5ndGgoKSAtIDEKICAgIAogICAgbGNzID0gQXJyYXkubmV3KG4rMSl7QXJyYXkubmV3KG0rMSwwKX0gCgogICAgMS51cHRvKG4pIHsgCgogICAgCXxpfAogICAgICAgIAogICAgCTEudXB0byhtKSB7CgogICAgCQl8anwKICAgICAgICAgICAgCiAgICAgICAgICAgIGlmIHhbaV0udG9faSA9PSB5W2pdLnRvX2kKICAgICAgICAgICAgICAgIAogICAgICAgICAgICAgICAgbGNzW2ldW2pdID0gMSArIGxjc1tpLTFdW2otMV0udG9faSAgICAgICAKICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgCiAgICAJCWVsc2UKCiAgICAJCQlsY3NbaV1bal0gPSBtYXgobGNzW2ldW2otMV0udG9faSwgbGNzW2ktMV1bal0udG9faSkKICAgIAkgICAgZW5kCiAgICAJfQogICAgICAgIAogICAgfSAKCiAgICBwIGxjc1tuXVttXQogICAgCiAgICBjcmVhdGVTdWIobGNzLCB4LCB5LCBuLCBtKQplbmQgICAKCm1haW4J