#include <stdio.h>
#define FIN "cmlsc.in"
#define FOUT "cmlsc.out"
#define maxsize 1024
typedef unsigned int u;
u max(u a, u b) {
if(a > b) return a;
else return b;
}
//global
u X[maxsize],
Y[maxsize],
ans[maxsize],
matLCS[maxsize][maxsize],
n, m;
u createMatrix() {
for(u i = 1; i <= n; ++i) {
for(u j = 1; j <= m; ++j) {
if(X[i] == Y[j]) {
matLCS[i][j] = 1 + matLCS[i-1][j-1];
} else {
matLCS[i][j] = max(matLCS[i][j-1], matLCS[i-1][j]);
}
}
}
return matLCS[n][m];
}
void createSubseq(u i, u j) {
if(i == 0 || j == 0) return;
if(X[i] == Y[j]) {
createSubseq(i - 1, j - 1);
printf("%d ", X[i]);
} else {
if(matLCS[i][j-1] < matLCS[i-1][j]) {
createSubseq(i - 1, j);
} else {
createSubseq(i, j - 1);
}
}
}
int main(int argc, char const *argv[])
{
//freopen(FIN, "r", stdin);
//freopen(FOUT, "w", stdout);
scanf("%d %d", &n, &m);
for(u i = 1; i <= n; ++i) {
scanf("%d", &X[i]);
}
for(u j = 1; j <= m; ++j) {
scanf("%d", &Y[j]);
}
printf("%d\n", createMatrix());
createSubseq(n, m);
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+CiNkZWZpbmUgRklOICJjbWxzYy5pbiIKI2RlZmluZSBGT1VUICJjbWxzYy5vdXQiCiNkZWZpbmUgbWF4c2l6ZSAxMDI0Cgp0eXBlZGVmIHVuc2lnbmVkIGludCB1OwoKdSBtYXgodSBhLCB1IGIpIHsKICAgICAgaWYoYSA+IGIpIHJldHVybiBhOwogICAgICAgICAgIGVsc2UgcmV0dXJuIGI7Cn0KCi8vZ2xvYmFsCnUgWFttYXhzaXplXSwgCiAgWVttYXhzaXplXSwgCiAgYW5zW21heHNpemVdLCAKICBtYXRMQ1NbbWF4c2l6ZV1bbWF4c2l6ZV0sIAogIG4sIG07Cgp1IGNyZWF0ZU1hdHJpeCgpIHsKICAKICBmb3IodSBpID0gMTsgaSA8PSBuOyAr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