//sakusen //dp[M][x] B_Mまで撮影し終え、しかもそのとき機会が一xにあるときの層移動コストの最小値 //B_M=A_xが必要 そうでないならてきとうに998244353(とてもおおきい)にでもしとけ #include using namespace std; int main(){ int N,Q; cin >> N >> Q; vector A(N+1); vector B(Q+1); for(int i=1;i<=N;i++){ cin >> A[i]; } for(int i=1;i<=Q;i++){ cin >> B[i]; } vector> dp(Q+1, vector(N+1)); for(int i=1;i<=N;i++){ if(A[i] == B[1]){ dp[1][i] = i-1; } else { dp[1][i] = 998244353; } } int min_temp = 998244353; int cost = 0; for(int m=2;m<=Q;m++){ for(int x=1;x<=N;x++){ //dp[m][x]求めるよ if(A[x] != B[m]){ dp[m][x] = 998244353; } else { min_temp = 998244353; for(int x_0=1;x_0<=N;x_0++){ cost = dp[m-1][x_0] + abs(x-x_0); if(cost < min_temp){ min_temp = cost; } } dp[m][x] = min_temp; } } } int min = 998244353; for(int x=1;x<=N;x++){ if(dp[Q][x] < min){ min = dp[Q][x]; } } cout << min << endl; }