Link to this code: https://cses.fi/paste/b4931c61c6f863cdd42c80/
// add me on genshin impact! 607984574
// Problem: Permutation Subsequence
// Attempted: 2025-07-29 11:39:58 EST

#include <bits/stdc++.h>
#ifndef LOCAL
#define debug(...) 0
#else
#include "/Users/envyaims/Documents/template/debug.cpp"
#endif
using namespace std;
using ll = long long;

#define F first
#define S second
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define pb push_back
#define pq priority_queue
#define FOR(i,a,b) for(int i = (a); i < (b); ++i)
#define FORE(i,a,b) for(int i = (a); i <= (b); ++i)
#define ROF(i,a,b) for(int i = (a); i >= (b); --i)
#define trav(a,x) for(auto& a: x)
#define sz(x) (int)x.size()
#define make_unique(v) v.erase(unique(all(v)), v.end());
 
template<class T> using minpq = pq<T, vector<T>, greater<T>>;
template<class T> bool ckmin(T& a, const T& b){return b<a?a=b,1:0;}
template<class T> bool ckmax(T& a, const T& b){return a<b?a=b,1:0;}
template<int D, typename T>struct vt : public vector<vt<D - 1, T>> { template<typename... Args>
	vt(int n = 0, Args... args) : vector<vt<D - 1, T>>(n, vt<D - 1, T>(args...)) {}};
template<typename T> struct vt<1, T> : public vector<T> {
	vt(int n = 0, const T& val = T()) : vector<T>(n, val) {}};
template<typename T> istream& operator>>(istream& in, vector<T>& a) {for(auto &x : a) in >> x; return in;};
template<typename T> ostream& operator<<(ostream& out, vector<T>& a) {for(auto &x : a) out << x << ' '; return out;};

struct segtree{
	using item = pair<int,int>;
	item merge(item a, item b){
		if(a.F > b.F) return a;
		return b;
	}
	item NEUTRAL = {0, -1};
	int n;
	vector<item> seg;
	segtree(int n){
		this->n = n;
		seg.resize(2 * n, NEUTRAL);
	}
	void update(int idx, int x){
		idx += n;
		seg[idx] = {x, idx-n};
		while(idx /= 2){
			seg[idx] = merge(seg[2 * idx], seg[2 * idx + 1]);
		}
	}
	item query(int l, int r){
		if(l > r) return NEUTRAL;
		item L = NEUTRAL, R = NEUTRAL;
		for(l += n, r += n + 1; l < r; l /= 2, r /= 2){
			if(l % 2 == 1){
				L = merge(L, seg[l++]);
			}
			if(r % 2 == 1){
				R = merge(seg[--r], R);
			}
		}
		return merge(L, R);
	}
};

void uwu(){
	int n, m; cin >> n >> m;
	vector<int> a(n), b(m); cin >> a >> b;
	vector<int> at_a(n+1);
	FOR(i,0,n) at_a[a[i]] = i;
	// now basically find the longest increasing subsequence in b
	FOR(i,0,m){
		if(b[i] <= n){
			b[i] = at_a[b[i]];
		}
		else{
			b[i] = -1;
		}
	}
	segtree st(n);
	vector<int> prv(n, -1);
	FOR(i,0,m){
		if(b[i] == -1) continue;
		auto q = st.query(0, b[i] - 1);
		st.update(b[i], q.F + 1);
		prv[b[i]] = q.S;
	}
	pair<int, int> mx = {0,0};
	FOR(i,0,n) ckmax(mx, {st.query(i,i).F, i});
	
	int cnt = mx.F, i = mx.S;
	cout << cnt << "\n";
	vector<int> v;
	while(cnt--){
		v.pb(a[i]);
		i = prv[i];
	}
	reverse(all(v));
	cout << v << "\n";
}

signed main(){
	cin.tie(0) -> sync_with_stdio(0);
	int t = 1;
	// cin>>t;
	while(t--){
		uwu();
	}
}