#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; } for (int u : A[B[j]]) { 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 } }); } } } return 0; }