/*
*
* Description: Longest Common Subsequence
*
* Author : Adrian Statescu <http://t...content-available-to-author-only...p.ch>
*
* License : MIT
*
*/
package main
import "fmt"
func max(a,b int) (int) {
if a > b {
return a
} else {
return b
}
}
func createSubseq(lcs [][]int, x []int, y []int, i int, j int) {
if i == 0 || j == 0 {
return
}
if x[i] == y[j] {
createSubseq(lcs, x, y, i-1, j-1)
fmt.Printf("%d ", x[i])
} else {
if(lcs[i][j-1] < lcs[i-1][j]) {
createSubseq(lcs, x, y, i - 1, j)
} else {
createSubseq(lcs, x, y, i, j - 1)
}
}
}
func main() {
x := []int{0,1,7,3,5,8}
y := []int{0,7,5,8,1}
var n, m int;
n = len(x)
m = len(y)
lcs := make([][]int, n)
for i:= range lcs {
lcs[i] = make([]int, m)
}
for i := 1; i <= n - 1; i++ {
for j := 1; j <= m - 1; j++ {
if x[i] == y[j] {
lcs[ i ][ j ] = 1 + lcs[i - 1][j - 1]
} else {
lcs[ i ][ j ] = max(lcs[i][j - 1], lcs[ i -1 ][ j ])
}
}
}
fmt.Printf("%d\n", lcs[n-1][m-1])
createSubseq(lcs, x, y, n - 1, m - 1)
i := n - 1
j := m - 1
var ans []int
for i != 0 && j != 0 {
if x[i] == y[j] {
ans = append(ans, x[i]) //push
i = i - 1
j = j - 1
} else {
if lcs[i][j-1] < lcs[i-1][j] {
i = i - 1;
} else {
j = j - 1;
}
}
}
fmt.Println("")
for len(ans) > 0 {
n := len(ans) - 1
fmt.Printf("%d ", ans[n]) //top element
ans = ans[:n] //pop
}
fmt.Println("")
}
LyoKICoKICogRGVzY3JpcHRpb246IExvbmdlc3QgQ29tbW9uIFN1YnNlcXVlbmNlCiAqCiAqIEF1dGhvciAgICAgOiBBZHJpYW4gU3RhdGVzY3UgPGh0dHA6Ly90Li4uY29udGVudC1hdmFpbGFibGUtdG8tYXV0aG9yLW9ubHkuLi5wLmNoPgogKiAKICogTGljZW5zZSAgICA6IE1JVAogKgogKi8KcGFja2FnZSBtYWluCgppbXBvcnQgImZ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ldID09IHlbal0gIHsKCiAgICAgICAgICAgICAgICBsY3NbIGkgXVsgaiBdID0gMSArIGxjc1tpIC0gMV1baiAtIDFdCgogICAgICAgICAgICAgfSBlbHNlIHsKCiAgICAgICAgICAgICAJbGNzWyBpIF1bIGogXSA9IG1heChsY3NbaV1baiAtIDFdLCBsY3NbIGkgLTEgXVsgaiBdKQoKICAgICAgICAgICAgIH0KICAgICAJIAkgCiAgICAgCSB9IAkKICAgICAJIAogICAgIH0KCiAgICAgZm10LlByaW50ZigiJWRcbiIsIGxjc1tuLTFdW20tMV0pIAoKICAgICBjcmVhdGVTdWJzZXEobGNzLCB4LCB5LCBuIC0gMSwgbSAtIDEpIAoKICAgICBpIDo9IG4gLSAxCiAgICAgaiA6PSBtIC0gMQoKICAgICB2YXIgYW5zIFtdaW50CgogICAgIGZvciBpICE9IDAgJiYgaiAhPSAwIHsKCiAgICAgICAgIGlmIHhbaV0gPT0geVtqXSB7CgogICAgICAgICAgICBhbnMgPSBhcHBlbmQoYW5zLCB4W2ldKSAvL3B1c2gKCiAgICAgICAgICAgIGkgPSBpIC0gMQogICAgICAgICAgICBqID0gaiAtIDEgICAgCgogICAgICAgICB9ICBlbHNlIHsKCiAgICAgICAgIAlpZiBsY3NbaV1bai0xXSA8IGxjc1tpLTFdW2pdIHsKCiAgICAgICAgIAkJaSA9IGkgLSAxOyAKCiAgICAgICAgIAl9IGVsc2UgewoKICAgICAgICAgCQlqID0gaiAtIDE7CiAgICAgICAgIAl9CgogICAgICAgICB9CiAgICAgfQoKICAgICBmbXQuUHJpbnRsbigiIikKCiAgICAgZm9yIGxlbihhbnMpID4gMCB7CgogICAgIAkgbiA6PSBsZW4oYW5zKSAtIDEKCiAgICAgCSBmbXQuUHJpbnRmKCIlZCAiLCBhbnNbbl0pIC8vdG9wIGVsZW1lbnQKCiAgICAgCSBhbnMgPSBhbnNbOm5dIC8vcG9wCiAgICAgfQoKICAgICBmbXQuUHJpbnRsbigiIikKfQ==