#include using namespace std; int main(int argc, char *argv[]) { int n, q; cin >> n >> q; map> A; for (int i = 0; i < n; i++) { int a; cin >> a; A[a].push_back(i); } vector B(q); for (int j = 0; j < q; j++) { cin >> B[j]; } //dijkstra //int cost = 0; vector> cost(q + 1); cost[0][0] = 0; for (int j = 0; j < q; j++) { for (int i : A[B[j]]) { cost[j + 1][i] = INT_MIN; } } priority_queue>> Q; Q.push( { 0, { 0, 0 } }); while (!Q.empty()) { int c; pair v; tie(c, v) = Q.top(); Q.pop(); int j; int i; tie(j, i) = v; if (j == q) { cout << -cost[j][i] << endl; break; } if (c < cost[j][i]) { continue; } vector::iterator lb = lower_bound(A[B[j]].begin(), A[B[j]].end(), i); vector::iterator ub = upper_bound(A[B[j]].begin(), A[B[j]].end(), i); int u = (lb == A[B[j]].end() ? A[B[j]].back() : *lb); int cst = cost[j][i] - abs(u - i); if (cst > cost[j + 1][u]) { cost[j + 1][u] = cst; Q.push( { cst, { j + 1, u } }); } if (ub != A[B[j]].end()) { u = *ub; cst = cost[j][i] - abs(u - i); if (cst > cost[j + 1][u]) { cost[j + 1][u] = cst; Q.push( { cst, { j + 1, u } }); } } } return 0; }