#include #include #define rep(i,n) for(int i=0;i vi; typedef vector vl; typedef vector> vvi; typedef vector> vvl; typedef long double ld; typedef pair P; ostream& operator<<(ostream& os, const modint& a) {os << a.val(); return os;} template ostream& operator<<(ostream& os, const static_modint& a) {os << a.val(); return os;} template ostream& operator<<(ostream& os, const dynamic_modint& a) {os << a.val(); return os;} template istream& operator>>(istream& is, vector& v){int n = v.size(); assert(n > 0); rep(i, n) is >> v[i]; return is;} template ostream& operator<<(ostream& os, const pair& p){os << p.first << ' ' << p.second; return os;} template ostream& operator<<(ostream& os, const vector& v){int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "\n" : " "); return os;} template ostream& operator<<(ostream& os, const vector>& v){int n = v.size(); rep(i, n) os << v[i] << (i == n - 1 ? "\n" : ""); return os;} template void chmin(T& a, T b){a = min(a, b);} template void chmax(T& a, T b){a = max(a, b);} struct Edge_BFS01{ int from, to; int cost; Edge_BFS01(int from, int to, int cost) : from(from), to(to), cost(cost) {}; }; const int INF = 1001001001; struct BFS01{ int n, m; vector initialized; vector E; vector> G; map> dist; map> idx; BFS01(int _n) : n(_n), m(0), initialized(n, false), G(n){} void add_edge(int from, int to, int cost){ assert(cost == 0 or cost == 1); Edge_BFS01 e(from, to, cost); E.push_back(e); G[from].emplace_back(m); m++; } void calc(int s){ initialized[s] = true; dist[s] = vector(n, INF); idx[s] = vector(n, -1); deque> de; de.emplace_back(0, s, -1); while(de.size()){ auto [cost, from, index] = de.front(); de.pop_front(); if(dist[s][from] <= cost) continue; dist[s][from] = cost; idx[s][from] = index; for(int index : G[from]){ int to = E[index].to; int cost_plus = E[index].cost; if(dist[s][to] <= cost + cost_plus) continue; if(cost_plus == 0) de.emplace_front(cost + cost_plus, to, index); if(cost_plus == 1) de.emplace_back(cost + cost_plus, to, index); } } } int get_dist(int s, int t){ if(!initialized[s]) calc(s); return dist[s][t]; } }; int main(){ int n, q; cin >> n >> q; vector a(n); vector b(q); cin >> a >> b; BFS01 graph(n * q + 1); int tv = n * q; rep(j, q){ rep(i, n - 1){ graph.add_edge(j * n + i, j * n + (i + 1), 1); graph.add_edge(j * n + (i + 1), j * n + i, 1); } rep(i, n){ if(a[i] == b[j]){ if(j != q - 1) graph.add_edge(j * n + i, (j + 1) * n + i, 0); else graph.add_edge(j * n + i, tv, 0); } } } int ans = graph.get_dist(0, tv); cout << ans << "\n"; return 0; }